[英]Nested Python for loop only works with the last item in a 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)
正如您在代码中看到的那样,我试图遍历列表中的每个项目,然后在循环的每个循环中循环,然后我想要 append 字符串“TEST”到当前循环通过第一个循环的单词的末尾。
让我们解析一个输入,例如"aword, anotherword, yetanotherword, certainword"
。 我希望该程序产生以下 output "awordTEST, anotherwordTEST, yetanotherwordTEST, certainwordTEST"
。
相反,这是实际的 output "aword, anotherword, yetanotherword, certainwordTEST"
。
我不明白为什么第二个循环只适用于列表中的最后一项。
编辑:建议的解决方案是使用单个 for 循环。 问题是我需要稍后使用第二个 for 循环,并且它在第二个 for 循环中很重要。 谢谢。
您需要更改此部分:
for each in list:
for i, item in enumerate(list):
joined = each + "TEST"
print(joined)
所以结果是
awordTEST
anotherwordTEST
yetanotherwordTEST
certainwordTEST
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.