"ValueError too many values to unpack" 在 for 循环中使用 str.split 时
"ValueError too many values to unpack" when using str.split in a for loop
我之前遇到过这个错误,原因很明显,但我在处理下面的代码片段时遇到了问题。
#!/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 个变量时,我得到:
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(":")
因为 e.split(":")
已经是一个具有三个值的可迭代对象。
如果你写
for (one, two, three) in something
那么something
必须是三值可迭代的可迭代,例如[[1, 2, 3], [4, 5, 6]]
,但不是 [1, 2, 3]
。
for (one, two, three) in e.split(':'):
需要e.split()
到return一个可迭代列表(例如二维列表)。 for
将迭代列表,并在迭代期间将嵌套列表的每个元素分配给对应的变量。
但是 e.split()
只是 return 一个字符串列表。您不需要迭代,只需分配它们:
one, two, three = e.split(':')
你可以使用这个:
one, two, three = e.split(':')
print 'one = "%s", two = "%s"' % (one, two)
我之前遇到过这个错误,原因很明显,但我在处理下面的代码片段时遇到了问题。
#!/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 个变量时,我得到:
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(":")
因为 e.split(":")
已经是一个具有三个值的可迭代对象。
如果你写
for (one, two, three) in something
那么something
必须是三值可迭代的可迭代,例如[[1, 2, 3], [4, 5, 6]]
,但不是 [1, 2, 3]
。
for (one, two, three) in e.split(':'):
需要e.split()
到return一个可迭代列表(例如二维列表)。 for
将迭代列表,并在迭代期间将嵌套列表的每个元素分配给对应的变量。
但是 e.split()
只是 return 一个字符串列表。您不需要迭代,只需分配它们:
one, two, three = e.split(':')
你可以使用这个:
one, two, three = e.split(':')
print 'one = "%s", two = "%s"' % (one, two)