将列表转换为具有多个变量的函数的输入的Pythonic方式 [英] Pythonic way of converting a list to inputs of a function of several variables
问题描述
由于不知道这一点,我开始感到有点愚蠢...
说我有两个变量的函数:
def testfun(x,y):返回x * y
现在我有一个值列表,例如 [2,3]
,我想将这些值作为值输入到函数中.最Python化的方法是什么?我想到了这样的东西:
def listfun(X):X_as_strs = str(X).strip('[]')表达式='testfun({0})'.format(X_as_strs)返回eval(表达式)
...但是它看起来非常不符合Python规范,无论如何我都不想处理字符串!是否有一种衬板(例如)会让我感觉到里面所有的刺痛和可爱(就像Python经常发生的那样)?我觉得这可能是一件疯狂的事……
*
表示法将在这里为您服务.
def testfun(x,y):返回x * ydef listfun(X):返回testfun(* X)>>>测试列表= [3,5]>>>listfun(测试列表)15>>>testfun(*测试列表)15
*
表示法专门用于解压缩函数调用列表.我还没有看到它可以在任何其他上下文中使用,但是调用 testfun(* [3,5])
等效于调用 testfun(3,5)
.>
I'm beginning to feel a little dumb for not figuring this out...
say I have a function of two variables:
def testfun(x,y):
return x*y
now I have a list of values, say [2,3]
, which I want to input as values into the function. What's the most Pythonic way to do this? I thought of something like this:
def listfun(X):
X_as_strs = str(X).strip('[]')
expression = 'testfun({0})'.format(X_as_strs)
return eval(expression)
... but it looks very un-pythonic and I don't want to deal with strings anyway! Is there a one liner (e.g.) that will make me feel all tingly and cuddly inside (like so often happens with Python)? I have a feeling it could be something crazy obvious...
The *
notation will serve you well here.
def testfun(x,y):
return x*y
def listfun(X):
return testfun(*X)
>>> testlist = [3,5]
>>> listfun(testlist)
15
>>> testfun(*testlist)
15
The *
notation is designed specifically for unpacking lists for function calls. I haven't seen it work in any other context, but calling testfun(*[3,5])
is equivalent to calling testfun(3,5)
.
这篇关于将列表转换为具有多个变量的函数的输入的Pythonic方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!