[英]Calling a function multiple times consecutively with different arguments in Python (3.x)?
I have a piece of code that looks like this:我有一段看起来像这样的代码:
myfunction(a, b, c)
myfunction(d, e, f)
myfunction(g, h, i)
myfunction(j, k, l)
The number of arguments do not change, but the function has to be called consecutively with different values each time.参数的数量不会改变,但必须每次使用不同的值连续调用该函数。 These values are not automatically generated and are manually inputted.
这些值不是自动生成的,而是手动输入的。 Is there an inline solution to do this without creating a function to call this function?
是否有内联解决方案可以在不创建函数来调用此函数的情况下执行此操作? Something like:
就像是:
myfunction(a, b, c)(d, e f)(g, h, i)(j, k, l)
Any help appreciated.任何帮助表示赞赏。 Thanks in advance!
提前致谢!
Simple, use tuple unpacking简单,使用元组解包
tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
print(myfunction(*tripple))
Hi I am not sure whether it's the most pythonic way , but if you have arguments defined as in a list the you can call the function in a loop, and remove the n argument from the beginning of the list :嗨,我不确定这是否是最 Pythonic 的方式,但是如果您在列表中定义了参数,则可以在循环中调用该函数,并从列表的开头删除 n 参数:
Have a look to the sample code :看看示例代码:
def myfunction(x1,x2,x3):
return x1+x2+x3
arglist = [1,2,3,4,5,6,7,8,9]
for _ in range(3):
print myfunction(arglist[_+0],arglist[_+1],arglist[_+2])
# remove used arguments from the list
arglist= arglist[2:]
你可以在这里滥用列表理解
[myfunction(*item) for item in ((a, b, c), (d, e, f), (g, h, i), (j, k, l))]
我想你想做的是这样的......
myfunction(myfunction(d, e, f), myfunction(g, h, i), myfunction(j, k, l))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.