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*ynow 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*ydef listfun(X): return testfun(*X)>>> testlist = [3,5]>>> listfun(testlist)15>>> testfun(*testlist)15The * 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方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-15 22:26