2014-01-10 55 views
3

爲什麼後面的兩個代碼片段會產生不同的錯誤? 我知道字符串是可迭代的,但我不明白爲什麼這裏很重要,因爲集合是被迭代的對象。嘗試解包集合時TypeError與ValueError

s = set([1, 2])   
for one, two in s: 
    print one, two 

引發

Traceback (most recent call last): 
    File "asdf.py", line 86, in <module> 
    for one, two in s: 
TypeError: 'int' object is not iterable 

s2 = set(['a', 'b']) 
for one, two in s2: 
    print one, two 

引發

Traceback (most recent call last): 
    File "asdf.py", line 90, in <module> 
    for one, two in s2: 
ValueError: need more than 1 value to unpack 

回答

6

字符串是一個序列太;你可以解開一個字符串成獨立的字符:

>>> a, b = 'cd' 
>>> a 
'c' 
>>> b 
'd' 

ValueError提高,因爲長度爲1的字符串不能被解壓到兩個目標。

但是,當循環遍歷整數序列時,您試圖將每個整數值解壓縮到兩個目標中,並且整數根本不可迭代。這是一個TypeError,因爲這是直接連接到對象的你正試圖解開類型:

>>> a, b = 42 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'int' object is not iterable 

與此相比,字符串,列表,元組,迭代器,發電機等,這些是所有類型的迭代。

如果你想直接解壓集,不使用for循環:

>>> a, b = set([1, 2]) 
>>> a 
1 
>>> b 
2 

但知道集沒有固定的順序(就像字典),以及在什麼樣的順序值分配取決於插入和刪除組的確切歷史。

+0

難道是有效地說,可迭代的,可以解壓? – Ben

+0

@Skim:絕對!只要迭代器產生滿足分配目標數量所需的確切元素數量。 –

+0

感謝您的解釋。 – Ben

2

您的for循環可能會超出您的預期。你試圖解開集合中的單個成員,而不是集合本身。在第一個例子中,成員是1,第二個成員是a。兩個值都沒有。

你可能想要的是one, two = s

您還可以找到這一點通過寫

>>> s = set([1, 2]) 
>>> for one_two in s: 
...  print one_two 
1 
2 
相關問題