2013-11-23 20 views
1

怪異的行爲我有一個奇怪的行爲與序列中的IPythonIPython的有序列拆封

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 

回答

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,它提出了語法錯誤:

>>> 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] 
+0

使用*語法不是在Python 2.7可用,以便拆包iterables是你的意思嗎? –

+0

謝謝任何​​想法我如何在Python 2.7 –

+0

@ jhon.smith,嘗試'頭,尾=項目[0],項目[1:]'。 – falsetru