问题
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...
回答1:
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).
来源:https://stackoverflow.com/questions/25571747/pythonic-way-of-converting-a-list-to-inputs-of-a-function-of-several-variables