“ValueError 值太多,无法解包"在 for 循环中使用 str.split 时 [英] "ValueError too many values to unpack" when using str.split in a for loop
本文介绍了“ValueError 值太多,无法解包"在 for 循环中使用 str.split 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我之前在原因很明显的地方遇到过这个错误,但我在处理下面的这个片段时遇到了问题.
I've gotten this error before where the cause was obvious, but I'm having trouble with this snippet below.
#!/usr/bin/python
ACL = 'group:troubleshooters:r,user:auto:rx,user:nrpe:r'
for e in ACL.split(','):
print 'e = "%s"' % e
print 'type during split = %s' % type(e.split(':'))
print 'value during split: %s' % e.split(':')
print 'number of elements: %d' % len(e.split(':'))
for (one, two, three) in e.split(':'):
print 'one = "%s", two = "%s"' % (one, two)
我已经添加了那些用于调试的打印语句,并确认拆分正在生成一个 3 元素列表,但是当我尝试将其放入 3 个变量时,我得到:
I've added those print statements for debugging, and have confirmed that the split is producing a 3-element list, but when I try to put that into 3 variables, I get:
e = "group:troubleshooters:r"
type during split = <type 'list'>
value during split: ['group', 'troubleshooters', 'r']
number of elements: 3
Traceback (most recent call last):
File "/tmp/python_split_test.py", line 10, in <module>
for (one, two, three) in e.split(':'):
ValueError: too many values to unpack
我错过了什么?
推荐答案
也许你应该:
one, two, three = e.split(":")
as e.split(":")
已经是一个具有三个值的可迭代对象.
as e.split(":")
is already an iterable with three values.
如果你写
for (one, two, three) in something
然后 something
必须是三个值的可迭代的迭代,例如[[1, 2, 3], [4, 5, 6]]
,但不是[1, 2, 3]
.
Then something
must be an iterable of iterable of three values, e.g. [[1, 2, 3], [4, 5, 6]]
, but not [1, 2, 3]
.
这篇关于“ValueError 值太多,无法解包"在 for 循环中使用 str.split 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文