将拆分字符串转换为元组导致“太多的值解包” [英] Convert a split string to a tuple results in "too many values to unpack"

查看:206
本文介绍了将拆分字符串转换为元组导致“太多的值解包”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在for循环中使用split会导致上述异常。但是,当从for循环中取出元素时,它是有效的:

 >>>打印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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆