为什么这一行会弄乱整个输出?
我正在尝试这样做:
输入:“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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在 for 循环中使用 insert 方法时,它会在迭代期间进行这些更新,从而在每次调用时更改每个索引处的值。
如果您在每次迭代结束时添加
print(test)
您应该明白我的意思。解决此问题的一种方法是创建一个与test
长度相同的列表,并在每次迭代时填充它。例如: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 astest
and fill it with each iteration. For example: