9阅网

您现在的位置是:首页 > 知识 > 正文

知识

python - 如何在Python函数中使用list数据类型作为参数?

admin2022-11-02知识15

目前,我开始学习Python。而我遇到了一个不清楚的情况。

例如,我有一段Java代码。

public String myMethod(List<String> listParam, int index) {
String str = listParam.get(index);
return str;
}

问题是--我应该如何在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 解释器本身并不关心注释,但有一些外部工具 (mypy)进行检查。你的代码就会像这样。

from typing import List

def myMethod(listParam: List[str], index: int) -> str:
    s: str = listParam[index]
    return s