简体   繁体   English

列表构造中的元组解包(python3)

[英]Tuple unpacking in list construction (python3)

I'd love to use tuple unpacking on the right hand side in assignments: 我喜欢在作业的右侧使用元组拆包:

>>> a = [3,4]

>>> b = [1,2,*a]
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

OF course, I can do: 当然,我可以这样做:

>>> b = [1,2]
>>> b.extend(a)
>>> b
[1, 2, 3, 4]

But I consider this cumbersome. 但我认为这很麻烦。 Am I mising a point? 我有点意思吗? An easy way? 一个简单的方法? Is it planned to have this? 它有计划吗? Or is there a reason for explicitly not having it in the language? 或者是否有理由明确没有使用该语言?

Part of the problem is that all container types use a constructor which expect an iterable and do not accept a *args argument. 部分问题是所有容器类型都使用构造函数,该构造函数期望迭代,并且不接受* args参数。 I could subclass, but that's introducing some non-pythonic noise to scripts that others are supposed to read. 我可以继承,但是这会给其他人应该阅读的脚本引入一些非pythonic噪声。

You could use add operator: 你可以使用add运算符:

a = [3, 4]
b = [1, 2] + a

You have a few options, but the best one is to use list concatenation ( + ): 您有几个选项,但最好的选择是使用列表连接( + ):

b = [1,2] + a

If you really want to be able to use the * syntax, you can create your own list wrapper: 如果您真的希望能够使用*语法,可以创建自己的列表包装器:

def my_list(*args):
    return list(args)

then you can call it as: 然后你可以称之为:

a = 3,4
b = my_list(1,2,*a)

I suppose the benefit here is that a doesn't need to be a list, it can be any Sequence type. 我想这里的好处是a不需要是列表,它可以是任何序列类型。

No, this is not planned. 不,这不是计划好的。 The *arg arbitrary parameter list (and **kw keyword arguments mapping) only applies to python call invocations (mirrored by *arg and **kw function signatures ), and to the left-hand side of an iterable assignment . *arg任意参数列表(和**kw关键字参数映射)仅适用于python 调用调用 (由*arg**kw函数签名镜像),并且适用于可迭代赋值的左侧。

You can simply concatenate the two lists: 您可以简单地连接两个列表:

b = [10, 2] + a

This is fixed in Python 3.5 as described in PEP 448 : PEP 448中所述,这在Python 3.5中得到修复:

>>> a=[3,4]
>>> b=[1,2,*a]
>>> b
[1, 2, 3, 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM