[英]Use not every argument of function in loop
I have got a function that has 2 arguments + 1 optional argument.我有一个 function 有 2 个 arguments + 1 个可选参数。 I want to run that function in loop basing on lists with different length and don't know how to really do it.我想基于不同长度的列表在循环中运行 function 并且不知道如何真正做到这一点。 The function and loop would look like this: function 和循环如下所示:
def function(x,y,z=1):
print(x,y,z)
LIST = [(1,1,1), (2,3,4), (5,6), (7,8), (9,9,9)]
for i in LIST:
print(function(i[0], i[1], i[2]))
of course I could write smth like if len(i) = 2: (...)
in loop but I wonder if I can do it a better way.当然,我可以像if len(i) = 2: (...)
in loop 那样写,但我想知道我是否可以做得更好。
The easiest way is to use *args
:最简单的方法是使用*args
:
def function(x, y, z=1):
print(x, y, z)
LIST = [(1,1,1), (2,3,4), (5,6), (7,8), (9,9,9)]
for i in LIST:
function(*i)
You can expand the tuple and pass it as argument as Pawel has mention.您可以扩展元组并将其作为 Pawel 提到的参数传递。 *args will not be needed in this case.在这种情况下不需要 *args。
def function(x,y,z=1):
print(x,y,z)
LIST = [(1,1,1), (2,3,4), (5,6), (7,8), (9,9,9)]
for i in LIST:
function(*i)
https://note.nkmk.me/en/python-argument-expand/ https://note.nkmk.me/en/python-argument-expand/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.