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

2024-09-27 07:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题,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)

正如您在代码中看到的,我尝试循环列表中的每个项目,然后在循环的每个循环中,然后在我想要将字符串“TEST”附加到当前循环第一个循环的单词的末尾之前

让我们分析一个输入,例如"aword, anotherword, yetanotherword, certainword"。我希望该程序产生以下输出"awordTEST, anotherwordTEST, yetanotherwordTEST, certainwordTEST"

相反,这是实际输出"aword, anotherword, yetanotherword, certainwordTEST"

我不明白为什么第二个循环只适用于列表中的最后一项

编辑:建议的解决方案是使用单个for循环。问题是,我需要在以后处理第二个for循环,这对第二个for循环很重要。谢谢


Tags: intest列表forinputlist嵌套循环each
2条回答

str.split不接受要拆分的正则表达式。如果查看list的内容,就会发现它只是原始字符串。如果要在正则表达式上拆分,必须使用the ^{} module

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!

我删除了内部循环,因为它只做乘法输出,并重命名了变量以避免名称隐藏内置项

您需要更改此部分:

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

所以结果是

awordTEST
anotherwordTEST
yetanotherwordTEST
certainwordTEST

相关问题 更多 >

    热门问题