Pythonic way of converting a list to inputs of a function of several variables [duplicate]

夙愿已清 提交于 2019-12-12 02:59:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!