>> print x x 但这给出了一个错误: >>> for x, y in "x=y".split("="): ... -6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:39 24 4
gpt4 key购买 nike

基本上这很好用:

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

但这给出了一个错误:

>>> 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

我想知道有什么区别,以及如何解决这个 for 循环。

最佳答案

拆分“=”给你两个值:

"x", "y"

这些值与您的变量名称匹配的事实是偶然的。你也可以这样做:

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

我怀疑您可能打算列一个 list :

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

然后拆分它,你可以这样做:

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

但是!虽然它有效,但我认为将它分成单独的步骤会更好,因为它更具可读性:

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

关于Python string.split for循环中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5044181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com