解包参数:只有命名参数可以跟在 *expression 之后 [英] Unpacking arguments: only named arguments may follow *expression

查看:32
本文介绍了解包参数:只有命名参数可以跟在 *expression 之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容在 Python 中运行良好:

The following works beautifully in Python:

def f(x,y,z): return [x,y,z]

a=[1,2]

f(3,*a)

a 的元素被解包,就像你调用它一样 f(3,1,2) 并返回 [3,1,2].太棒了!

The elements of a get unpacked as if you had called it like f(3,1,2) and it returns [3,1,2]. Wonderful!

但是我无法将 a 的元素解包到 first 两个参数中:

But I can't unpack the elements of a into the first two arguments:

f(*a,3)

我得到的不是像 f(1,2,3) 这样的调用,而是SyntaxError:只有命名参数可以跟在 *expression 之后".

Instead of calling that like f(1,2,3), I get "SyntaxError: only named arguments may follow *expression".

我只是想知道为什么必须这样,如果有任何我可能不知道的聪明技巧,可以将数组解包到参数列表的任意部分而不诉诸临时变量.

I'm just wondering why it has to be that way and if there's any clever trick I might not be aware of for unpacking arrays into arbitrary parts of argument lists without resorting to temporary variables.

推荐答案

正如 Raymond Hettinger 的回答所指出的,这在 Python 3 和 这里有一个相关的提案,已经被接受.特别是与当前问题相关,这里是讨论的提案的可能更改之一:

As Raymond Hettinger's answer points out, this may change has changed in Python 3 and here is a related proposal, which has been accepted. Especially related to the current question, here's one of the possible changes to that proposal that was discussed:

只允许带星号的表达式作为表达式列表中的最后一项.这将简化稍微解压代码并允许为带星号的表达式分配一个迭代器.这个行为被拒绝,因为这太令人惊讶了.

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.

所以解包函数参数的限制是有实现原因的,但确实有点令人惊讶!

So there are implementation reasons for the restriction with unpacking function arguments but it is indeed a little surprising!

与此同时,这是我正在寻找的解决方法,回想起来很明显:

In the meantime, here's the workaround I was looking for, kind of obvious in retrospect:

f(*(a+[3]))

这篇关于解包参数:只有命名参数可以跟在 *expression 之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆