尝试解压缩集时出现TypeError与ValueError

Ben*_*Ben 3 python iterable-unpacking

为什么跟随两个代码片段会产生不同的错误?我理解字符串是可迭代的,但是我不明白为什么这在这里很重要,因为集合是被迭代的对象.

s = set([1, 2])        
for one, two in s:
  print one, two
Run Code Online (Sandbox Code Playgroud)

加薪

Traceback (most recent call last):
  File "asdf.py", line 86, in <module>
    for one, two in s:
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)
s2 = set(['a', 'b'])
for one, two in s2:
  print one, two 
Run Code Online (Sandbox Code Playgroud)

加薪

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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

字符串也是一个序列; 你可以将字符串解压缩成单独的字符:

>>> a, b = 'cd'
>>> a
'c'
>>> b
'd'
Run Code Online (Sandbox Code Playgroud)

ValueError升高,因为长度为1的串不能被解压缩到两个目标.

但是,当循环遍历整数序列时,您试图将每个整数值解包为两个目标,并且整数根本不可迭代.这是一个TypeError,因为它直接连接到您要解压缩的对象类型:

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

将其与字符串,列表,元组,迭代器,生成器等进行比较,它们都是可迭代的类型.

如果要直接解压缩集,请不要使用for循环:

>>> a, b = set([1, 2])
>>> a
1
>>> b
2
Run Code Online (Sandbox Code Playgroud)

但是要知道集合没有固定的顺序(就像字典一样),并且值的分配顺序取决于插入和删除集合的确切历史.