简体   繁体   English

Python string.split for循环中有多个值

[英]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. 您尝试的是迭代序列["x", "y"] ,但为序列的每个条目分配x, y 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循环:

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

Because the split function is returning a list. 因为split函数返回一个列表。 In the context of a for loop, it gets one item at a time. 在for循环的上下文中,它一次获得一个项目。 Eg: 'k=y'.split('=') returns a list containing ['k', 'y'] . 例如: 'k=y'.split('=')返回包含['k', 'y'] Since it's in the for loop you get 'k', then 'y'. 因为它在for循环中你得到'k',然后'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. 它在for循环之外工作的原因是因为它在for循环中一次看到整个列表而不是一个项目,并且能够解压缩它。

To fix it, you could split the data into a list of tuples outside the for loop, and loop through that. 要修复它,您可以将数据拆分为for循环外的元组列表,然后循环遍历。 Eg: [('x', 'y'), ...] 例如: [('x', 'y'), ...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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