代码之家  ›  专栏  ›  技术社区  ›  Jeremy Koppel

在for循环中使用str.split时,“ValueError太多值无法解压缩”

  •  4
  • Jeremy Koppel  · 技术社区  · 6 年前

    我以前遇到过这个错误,原因很明显,但我在下面的代码片段中遇到了问题。

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

    我错过了什么?

    3 回复  |  直到 5 年前
        1
  •  7
  •   Georgy rassa45    5 年前

    也许你应该:

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

    e.split(":") 已是具有三个值的iterable。

    如果你写信

    for (one, two, three) in something
    

    然后 something 必须是三个值的iterable中的iterable,例如。 [[1, 2, 3], [4, 5, 6]] ,但不是 [1, 2, 3]

        2
  •  5
  •   Barmar 0___________    6 年前
    for (one, two, three) in e.split(':'):
    

    需要 e.split() 返回iterables列表(例如,二维列表)。 for 将在列表上迭代,并在迭代期间将嵌套列表的每个元素分配给共同响应的变量。

    但是 e、 拆分() 只返回单个字符串列表。您不需要迭代,只需分配它们:

    one, two, three = e.split(':')
    
        3
  •  0
  •   Marco Túlio Teixeira    6 年前

    您可以使用此选项:

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