简体   繁体   中英

Python string.split more than one value in for loop

Basically this works fine:

>>> x,y = "x=y".split("=")
>>> print x
x

But this gives an error:

>>> for x, y in "x=y".split("="):
...     print x
...

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

I am wondering what the difference is, and how I could fix this for loop.

Split on "=" gives you two values:

"x", "y"

The fact that those values match your variable names is incidental. You could also do:

x,xx = "x=y".split("=")

I suspect what you are likely planning is to take a list:

"foo=bar,blah=boo,etc=something"

And split it, for which you could do:

for x,y in [ (pair.split("=")) for pair in "foo=bar,blah=boo,etc=something".split(",") ]:
    print x,y

BUT! While it works, I think it would be much better to split it into individual steps as it's much more readable:

params = "foo=bar,blah=boo,etc=something"
pair_list = params.split(",")
for pair in pair_list:
    x,y = pair.split("=")
    ...

You could do

for x in "x=y".split("="):
    # ...

What you tried is to iterate over the sequence ["x", "y"] , but assign to x, y for each entry of the sequence. That would be equivalent to

 x, y = "x"

for the first iteration, which does not make any sense.

I'm not sure why you would ever want to do this, but if for some reason you would like to use a for loop for this:

>>> for x, y in ["x=y".split("=")]:
...   print x
...   print y
... 
x
y

Because the split function is returning a list. In the context of a for loop, it gets one item at a time. Eg: 'k=y'.split('=') returns a list containing ['k', 'y'] . Since it's in the for loop you get 'k', then 'y'.

The reason it works outside of the for loop is because it sees the entire list at once versus one item at a time in the for loop and is able to unpack it.

To fix it, you could split the data into a list of tuples outside the for loop, and loop through that. Eg: [('x', 'y'), ...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM