Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

python - Convert a split string to a tuple results in "too many values to unpack"

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...