简体   繁体   English

嵌套的 Python for 循环仅适用于列表中的最后一项

[英]Nested Python for loop only works with the last item in a list

I have encountered an issue where the 2nd for loop in a nested loop in Python only works for the last item in the list.我遇到了一个问题,即 Python 中嵌套循环中的第二个 for 循环仅适用于列表中的最后一项。

input = input("Words: ")
print(input)
list = input.split('[:,\s]')
print(list)

for each in list:
    for i, item in enumerate(list):
        joined = each + "TEST"
        print(joined)

As you can see in the code I am trying to loop through every item in the list and then in each loop of the loop before I want to append the string "TEST" to the end of the word that's currently looped through first loop.正如您在代码中看到的那样,我试图遍历列表中的每个项目,然后在循环的每个循环中循环,然后我想要 append 字符串“TEST”到当前循环通过第一个循环的单词的末尾。

Let's parse an input for example "aword, anotherword, yetanotherword, certainword" .让我们解析一个输入,例如"aword, anotherword, yetanotherword, certainword" I would expect the program to produce the following output "awordTEST, anotherwordTEST, yetanotherwordTEST, certainwordTEST" .我希望该程序产生以下 output "awordTEST, anotherwordTEST, yetanotherwordTEST, certainwordTEST"

Instead this is the actual output "aword, anotherword, yetanotherword, certainwordTEST" .相反,这是实际的 output "aword, anotherword, yetanotherword, certainwordTEST"

I can't figure out why does the 2nd loop only work for the last item in the list.我不明白为什么第二个循环只适用于列表中的最后一项。

Edit: suggested solution was to use a single for loop.编辑:建议的解决方案是使用单个 for 循环。 The thing is that I need to work with that 2nd for loop later and it is important for it to be in that 2nd for loop.问题是我需要稍后使用第二个 for 循环,并且它在第二个 for 循环中很重要。 Thanks.谢谢。

str.split does not accept regular expressions to split on. str.split不接受要拆分的正则表达式。 If you look at the contents of list , you'll see it's just the original string.如果您查看list的内容,您会发现它只是原始字符串。 If you want to split on a regex, you must use the re module :如果要拆分正则表达式,则必须使用re模块

import re

inp = input("Words: ")
print(inp)
lst = re.split(r'[:,\s]+', inp)
print(lst)

for each in lst:
    joined = each + "TEST"
    print(joined)

Try it online! 在线尝试!

I removed the inner loop because it was doing nothing but multiplying outputs, and renamed variables to avoid name-shadowing built-ins.我删除了内部循环,因为它除了乘以输出之外什么都不做,并重命名变量以避免名称隐藏内置函数。

you need change this section:您需要更改此部分:

for each in list:
    for i, item in enumerate(list):
        joined = each + "TEST"
    print(joined)

so the result is所以结果是

awordTEST
anotherwordTEST
yetanotherwordTEST
certainwordTEST

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

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