如何在Python函数中使用列表数据类型作为参数?
目前,我开始学习Python。我面临着一个不明朗的局面 例如,我有一段Java代码:如何在Python函数中使用列表数据类型作为参数?,python,list,parameters,Python,List,Parameters,目前,我开始学习Python。我面临着一个不明朗的局面 例如,我有一段Java代码: public String myMethod(List<String> listParam, int index) { String str = listParam.get(index); return str; } 公共字符串myMethod(列表listParam,int索引){ String str=listParam.get(索引); 返回str; } 问题是-我如何/应该在Python
public String myMethod(List<String> listParam, int index) {
String str = listParam.get(index);
return str;
}
公共字符串myMethod(列表listParam,int索引){
String str=listParam.get(索引);
返回str;
}
问题是-我如何/应该在Python中做同样的事情?
有人能给我一段类似Python的代码吗?你可以试试这个
def myMethod(list_param, index):
return list_param[index]
你可以用这样的东西
def myMethod(listParam, index):
return listParam[index]
您只需使用列表变量上的索引号,示例如下所示:
# list_variable
name_list = ["foo", "bar", "apple", "orange"]
# using index to get value of respective element
my_name = name_list[0]
favourite_fruit = name_list[2]
# printing the values
print(my_name)
print(favourite_fruit)
# output
foo
apple
传统上Python不声明变量类型。最新版本支持(但不强制)静态类型注释(请参阅)。Python解释器本身并不关心注释,但是有外部工具()用于检查。您的代码将如下所示:
from typing import List
def myMethod(listParam: List[str], index: int) -> str:
s: str = listParam[index]
return s