首页 文章

Python ValueError要解压的值太多 - 不是真的吗?

提问于
浏览
2

我之前在原因很明显的地方得到了这个错误,但我在下面的这个片段中遇到了麻烦 .

#!/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)

我已经添加了那些用于调试的print语句,并且已经确认拆分正在生成一个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

我错过了什么?

3 回答

  • 3

    也许你应该:

    one, two, three = e.split(":")
    

    因为 e.split(":") 已经是一个具有三个值的可迭代 .

    如果你写

    for (one, two, three) = something
    

    那么 something 必须是可迭代的三个值的迭代,例如 [[1, 2, 3], [4, 5, 6]] ,但不是 [1, 2, 3] .

  • 0
    for (one, two, three) in e.split(':'):
    

    需要 e.split() 来返回可迭代的列表(例如,二维列表) . for 将遍历列表,并在该迭代期间将嵌套列表的每个元素分配给相应的变量 .

    e.split() 只返回一个字符串列表 . 您不需要迭代,只需分配它们:

    one, two, three = e.split(':')
    
  • 6

    你可以用这个:

    one, two, three = e.split(':')
    print 'one = "%s", two = "%s"' % (one, two)
    

相关问题