简体   繁体   English

不要在循环中使用 function 的每个参数

[英]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.

相关问题 Python函数不会为内部循环中的每次迭代调用给定参数 - Python function does not call given argument for every iteration in inner loop 在循环外使用 For 循环参数? - Use For loop argument outside the loop? 如何使用日志过滤器而不将结果记录器作为额外参数传递给每个函数? - How to use logging filter without passing resulting logger as an extra argument to every function? 在 Pythone 中使用 function 作为参数 - Use function as an argument in Pythone DataFrames 列表作为函数/循环的参数 - list of DataFrames as an argument of function/loop 如何将函数作为参数传递,并强制此函数使用 Python 中来自外循环的索引值? - How to pass function as an argument, and force this function to use index values from outer loop in Python? 将 For 循环转换为函数 python 和函数参数说明 - Convert a For loop to a function python and function argument clarification 使用函数作为函数参数在 with 语句中使用 - use a function as function argument to use in with statement 如何遍历 Pyspark RDD 中的每一行并将它们转换为键? 使用地图功能? - How can I loop over every item a row in Pyspark RDD and turn them into keys? Use map function? 在 Python 中的函数中使用 input() 作为参数 - Use input() as an argument in a function in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM