为什么跟随两个代码片段会产生不同的错误?我理解字符串是可迭代的,但是我不明白为什么这在这里很重要,因为集合是被迭代的对象.
s = set([1, 2]) for one, two in s: print one, two
加薪
Traceback (most recent call last): File "asdf.py", line 86, infor 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, infor one, two in s2: ValueError: need more than 1 value to unpack
Martijn Piet.. 6
字符串也是一个序列; 你可以将字符串解压缩成单独的字符:
>>> a, b = 'cd' >>> a 'c' >>> b 'd'
的ValueError
升高,因为长度为1的串不能被解压缩到两个目标.
但是,当循环遍历整数序列时,您试图将每个整数值解包为两个目标,并且整数根本不可迭代.这是一个TypeError
,因为它直接连接到您要解压缩的对象类型:
>>> a, b = 42 Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable
将其与字符串,列表,元组,迭代器,生成器等进行比较,它们都是可迭代的类型.
如果要直接解压缩集,请不要使用for
循环:
>>> a, b = set([1, 2]) >>> a 1 >>> b 2
但是要知道集合没有固定的顺序(就像字典一样),并且值的分配顺序取决于插入和删除集合的确切历史.
字符串也是一个序列; 你可以将字符串解压缩成单独的字符:
>>> 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
但是要知道集合没有固定的顺序(就像字典一样),并且值的分配顺序取决于插入和删除集合的确切历史.