[英]Python in-place unpacking doesn't seem to work as expected
I've seen a lot of questions on here about using *
before a tuple to expand it into something else, but it doesn't seem to work for me. 我在这里看到很多关于在元组之前使用
*
将其扩展为其他内容的问题,但是它似乎对我不起作用。
>>> l1 = (1, 2, 3)
>>> l2 = (0, l1, 4)
>>> l2 (0, (1, 2, 3), 4)
>>> l2 = (0, *l1, 4)
File "<stdin>", line 1
l2 = (0, *l1, 4)
^ SyntaxError: invalid syntax
As you can see. 如你看到的。 I can't get l1 to expand into l2 with the
*
operator... 我无法使用
*
运算符将l1扩展为l2 ...
Note: This is python2.7 注意:这是python2.7
In-place unpacking has been introduced in python 3.5 and it works in later versions not older ones. 就地解包已在python 3.5中引入,它在较新的版本中起作用,而不是较旧的版本。
# Python 3.5
In [39]: (3, *l1, 4)
Out[39]: (3, 1, 2, 3, 4)
In older versions you can use +
operator or itertools.chain
function for longer iterables: 在较旧的版本中,可以使用
+
运算符或itertools.chain
函数来实现更长的可迭代项:
In [40]: (3,) + l1 + (4,)
Out[40]: (3, 1, 2, 3, 4)
In [41]: from itertools import chain
In [45]: tuple(chain((3,), l1, (4,)))
Out[45]: (3, 1, 2, 3, 4)
First of all, those aren't lists
, they're tuples
. 首先,这些不是
lists
,而是tuples
。 They are similar but not the same thing. 它们是相似但不相同的东西。
Second, the *arg
syntax is called argument expansion , and it only works for function arguments 其次,
*arg
语法称为自变量扩展 ,它仅适用于函数自变量
def func(a, b):
return a + b
my_list = [1, 2]
func(*my_list)
EDIT: 编辑:
Apparently, in-place unpacking was added in python 3.5, but for the overwhelming majority of python installations you encounter, my answer still holds true. 显然,在python 3.5中添加了就地拆包,但是对于您遇到的绝大多数python安装,我的回答仍然成立。 Perhaps in 2020 when Python 2 stops being supported this will change, but for now and the immediate future, expect the above to be true.
也许在2020年停止支持Python 2时,这种情况将会改变,但是就目前和不久的将来而言,希望以上内容是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.