Python 函数内部动态参数处理

问题描述 投票:0回答:1

我的以下代码不起作用。

def myFunction(*args):

    total_lists = len(args)

    for n in range(total_lists):
        print(list(zip(args[0], args[1])))


myFunction([1,2,3],["a", "b", "c"])

基本上函数接收未知数量的参数,因为

lists
具有相同数量的值,需要像这样逐行输出每个列表

1,a
2,b
3,c

如果使用三个参数调用则

myFunction([1,2,3],["a", "b", "c"], ["one", "two", "three"])

应该输出

1,a,one
2,b,two
3,c,three

我无法控制有多少列表将传递给函数,因此我无法在发送之前混合它们,只能在函数内部处理,我如何使其动态工作?

python function loops for-loop tuples
1个回答
0
投票

使用

zip(*args)

def my_function(*args):
    for p in zip(*args):
        print(list(p))


my_function([1, 2, 3], ["a", "b", "c"], [1.1, 1.2, 1.3])

打印:

[1, 'a', 1.1]
[2, 'b', 1.2]
[3, 'c', 1.3]
© www.soinside.com 2019 - 2024. All rights reserved.