爲什麼後面的兩個代碼片段會產生不同的錯誤? 我知道字符串是可迭代的,但我不明白爲什麼這裏很重要,因爲集合是被迭代的對象。嘗試解包集合時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
難道是有效地說,可迭代的,可以解壓? – Ben
@Skim:絕對!只要迭代器產生滿足分配目標數量所需的確切元素數量。 –
感謝您的解釋。 – Ben