“ValueError too many values to unpack” when using str.split in a for loop

时光怂恿深爱的人放手 提交于 2020-01-14 13:45:28

问题


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)

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

What am I missing?


回答1:


Maybe you should:

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

as e.split(":") is already an iterable with three values.

If you write

for (one, two, three) in something

Then something must be an iterable of iterable of three values, e.g. [[1, 2, 3], [4, 5, 6]], but not [1, 2, 3].




回答2:


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

requires e.split() to return a list of iterables (e.g. a 2-dimensional list). for will iterate over the list, and assign each element of the nested list to the coresponding variables during that iteration.

But e.split() just returns a single list of strings. You don't need to iterate, just assign them:

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



回答3:


You can use this:

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


来源:https://stackoverflow.com/questions/50054003/valueerror-too-many-values-to-unpack-when-using-str-split-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!