为什么这一行会弄乱整个输出?

发布于 2025-01-14 22:17:59 字数 545 浏览 2 评论 0原文

我正在尝试这样做:

输入:“4of Fo1r pe6ople g3ood th5e the2”

输出:“Fo1r the2 g3ood 4of th5e pe6ople”

使用此代码:

test = "4of Fo1r pe6ople g3ood th5e the2"
test = test.split()
x = 0
for i in test:
    x = re.search("[1-9]", i)
    x = int(x.group(0))-1
    test.insert(x, test.pop(test.index(i)))

但由于某种原因,For 循环中的最后一行破坏了 x 的输出(其中是字符串列表中元素的新索引)。

最后一行之前(每次迭代后打印 x):

3

0

5

2

1

最后一行之后(每次迭代后打印 x):

3

5

3

3

1

5

I'm trying to do this:

input: "4of Fo1r pe6ople g3ood th5e the2"

output: "Fo1r the2 g3ood 4of th5e pe6ople"

Using this code:

test = "4of Fo1r pe6ople g3ood th5e the2"
test = test.split()
x = 0
for i in test:
    x = re.search("[1-9]", i)
    x = int(x.group(0))-1
    test.insert(x, test.pop(test.index(i)))

But for some reason the last line in the For loop ruins the outputs of x (which are the new indexes for the elements in the list of strings).

Before the last line (printing x after each iteration):

3

0

5

2

1

After the last line (printing x after each iteration):

3

5

3

3

1

5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千鲤 2025-01-21 22:17:59

当您在 for 循环中使用 insert 方法时,它会在迭代期间进行这些更新,从而在每次调用时更改每个索引处的值。

如果您在每次迭代结束时添加 print(test) 您应该明白我的意思。解决此问题的一种方法是创建一个与 test 长度相同的列表,并在每次迭代时填充它。例如:

test = "4of Fo1r pe6ople g3ood th5e the2"
test = test.split()
x = 0
new_list = [0] * len(test)
for i in test:
    x = re.search("[1-9]", i)
    x = int(x.group(0))-1
    new_list[x] = i

When you use the insert method inside a for loop it makes those updates during the iteration, thus changing the values at each index with every call.

If you add print(test) at the end of each iteration you should see what I mean. One way to fix this problem is to create a list with the same length as test and fill it with each iteration. For example:

test = "4of Fo1r pe6ople g3ood th5e the2"
test = test.split()
x = 0
new_list = [0] * len(test)
for i in test:
    x = re.search("[1-9]", i)
    x = int(x.group(0))-1
    new_list[x] = i
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文