繁体   English   中英

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

[英]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 循环中很重要。 谢谢。

str.split不接受要拆分的正则表达式。 如果您查看list的内容,您会发现它只是原始字符串。 如果要拆分正则表达式,则必须使用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)

在线尝试!

我删除了内部循环,因为它除了乘以输出之外什么都不做,并重命名变量以避免名称隐藏内置函数。

您需要更改此部分:

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.

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