如何在函数中使用多个列表作为参数并以不同方式接收它们?

时间:2014-11-26 03:20:31

标签: python python-2.7

假设我有三个清单,

a = [1,2,3]
b = [2,3,4]
c = [4,5,6]

并在函数中接收它们:

def foo(x,y,z):
    """I will print or use x,y, and z differently"""

foo(a,b,c)

我知道我可以在Python中使用(* args)传递一个列表:

foo(*x)

但是在这里,x解压缩每个列表中的项目并将它们存储在自身中。

我希望我的函数能够在不同的参数中单独接受列表。

1 个答案:

答案 0 :(得分:3)

你可以这样做:

def foo(*x):    # x will always will be tuple, whatever you pass
    """I will print or use x,y, and z differently"""
    for i in range(len(x)):   
        print(x[i])           # instead of printing, you can assign values

演示:

>>> foo([1,2,3,4],[5,6,7,8],[3,5,6,3])
[1, 2, 3, 4]
[5, 6, 7, 8]
[3, 5, 6, 3]

如果您不想使用范围

>>> def foo(*x):
...     print(x)
...     for i in x:
...         print(i)
... 

输出:

([1, 2, 3, 4], [5, 6, 7, 8], [3, 5, 6, 3])  # you can see its tuple containing list
[1, 2, 3, 4]
[5, 6, 7, 8]
[3, 5, 6, 3]