使用序列解包的ipython怪异行为

时间:2013-11-23 14:08:08

标签: python ipython

我在ipython

中使用序列解包有一个奇怪的行为
In [12]: items = [1, 10, 7, 4, 5, 9]

In [13]: head, *tail = items
  File "<ipython-input-13-34256df22cca>", line 1
    head, *tail = items
          ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:3)

这种语法(PEP 3132 - Extended Iterable Unpacking)是在Python 3.0中引入的。检查你的python版本。

在Python 3.3中:

>>> items = [1, 10, 7, 4, 5, 9]
>>> head, *tail = items
>>> head
1
>>> tail
[10, 7, 4, 5, 9]

在Python 2.7中,它引发了SyntaxError:

>>> items = [1, 10, 7, 4, 5, 9]
>>> head, *tail = items
  File "<stdin>", line 1
    head, *tail = items
          ^
SyntaxError: invalid syntax
>>> head, tail = items[0], items[1:] # workaround
>>> head
1
>>> tail
[10, 7, 4, 5, 9]