以下代码在 Python 中运行良好:
def f(x,y,z): return [x,y,z]
a=[1,2]
f(3,*a)
a
的元素被解包,就好像你像 f(3,1,2)
一样调用它,它返回 [3,1,2 ]
。太棒了!
但我无法将 a
的元素解压缩到 first 两个参数中:
f(*a,3)
我没有像 f(1,2,3)
那样调用它,而是得到“SyntaxError: only named arguments may follow *expression”。
我只是想知道为什么必须这样,如果有什么聪明的技巧我可能不知道,可以将数组解压缩到参数列表的任意部分而不求助于临时变量。
最佳答案
正如 Raymond Hettinger 的回答所指出的,这可能会改变在 Python 3 和 here is a related proposal 中已经改变了。 , 已被接受。
尤其是与当前问题相关,以下是所讨论的提案的可能更改之一:
Only allow a starred expression as the last item in the exprlist. This would simplify the unpacking code a bit and allow for the starred expression to be assigned an iterator. This behavior was rejected because it would be too surprising.
所以解包函数参数的限制是有实现原因的,但这确实有点令人惊讶!
与此同时,这是我一直在寻找的解决方法,回想起来有点明显:
f(*(a+[3]))
关于python - 解包参数 : only named arguments may follow *expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720450/