将拆分字符串转换为元组导致“太多的值解包” [英] Convert a split string to a tuple results in "too many values to unpack"
问题描述
>>>打印k,v
...
Traceback(最近一次调用的最后一个):
文件k,v in x.split(=): < stdin>,第1行,在< module>
ValueError:太多值来解开
>>> y = x.split(=)
>>> y
['abc','asflskfjla']
>>> k,v = y
>>> k
'abc'
>>> v
'asflskfjla'
一个解释将会被赞赏 - for循环版本。
循环的在迭代器中可以解压成两个变量。所以在你的情况下,它看起来像这样的一个:
[('a,b'), c,d'),...]
[['a,b'],['c,d'],...]
['ab','cd',.. 。]
...
每个可迭代项中的每一项都可以分成一个 k
和一个 v
组件。在你的情况下,它们不能,因为 x.split('=')
的输出是一个包含两个以上字符的字符串列表:
['abc','asflskfjla']
Using split in a for loop results in the mentioned exception. But when taking the elements indpendent from a for loop it works:
>>> for k,v in x.split("="):
... print k,v
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> y = x.split("=")
>>> y
['abc', 'asflskfjla']
>>> k,v = y
>>> k
'abc'
>>> v
'asflskfjla'
An explanation would be appreciated - and also naturally the proper syntax for the for loop version.
The for
loop expects that each item in the iterable can be unpacked into two variables. So in your case, it'd look something like one of these:
[('a, b'), ('c, d'), ...]
[['a, b'], ['c, d'], ...]
['ab', 'cd', ...]
...
Each item in each of those iterables can be split up into a k
and a v
component. In your case, they cannot, as the output of x.split('=')
is a list of strings with more than two characters:
['abc', 'asflskfjla']
这篇关于将拆分字符串转换为元组导致“太多的值解包”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!