在Python中列为函数参数

时间:2016-04-22 06:27:20

标签: python list function arguments

如果我试图在Python中输入一个列表作为函数的参数,有没有办法将参数保留为列表,还是一次只能在一个元素中传递?

4 个答案:

答案 0 :(得分:4)

如果按原样传递列表,则它将保留为列表。

>>> def myfunc(*args):
        for arg in args:
            print(arg)
>>> sample_list = [1, 2, 3]
>>> myfunc(sample_list)
[1, 2, 3]

该功能将列表打印为一个项目。

但是,如果你使用' splat'或者'打开包装'运算符*,列表可以作为多个参数传递。

>>> myfunc(*sample_list)
1
2
3

答案 1 :(得分:0)

这不是答案,但在评论/

中制作代码很难

可能你的意思是:

def f(a, b):
    print("f(%s, %s)" % (a, b))

l = [1, 2]
f(*l)

答案 2 :(得分:0)

您正在寻找的语法是:

my_list = ["arg1", "arg2", None, 4, "arg5"]
print(*my_list)

相当于:

print("arg1", "arg2", None, 4, "arg5")

答案 3 :(得分:0)

您获取作为参数传递的函数内的对象。如果你的参数是一个列表,那么你在函数内部得到一个列表,当然是一个正确的列表而不是单个变量。

def func1(my_list):
    print(type(my_list), my_list)

func1([1, 2, "abc"])

# output: <type 'list'> [1, 2, "abc"]

但是,您可以使用多种方法来实现其他目标。你可以......

  1. 调用函数时传递单个参数,但将所有参数作为单个元组(不可变列表)接收。

    def func2(*my_list):  # the * means that this parameter collects 
                          # all remaining positional arguments
        print(type(my_list), my_list)
    
    func2(1, 2, "abc")
    
    # output: <type 'tuple'> (1, 2, "abc")
    
  2. 在函数调用中解压缩列表并将元素作为单个参数接收。

    def func2(arg1, arg2, arg3):
        print(type(arg1), arg1, type(arg2), arg2, type(arg3), arg3)
    
    func2(*[1, 2, "abc"])  # the * unpacks the list to single positional arguments
    
    # output: <type 'int'> 1 <type 'int'> 2 <type 'str'> abc