我遇到了一个问题,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循环很重要。谢谢
str.split
不接受要拆分的正则表达式。如果查看list
的内容,就会发现它只是原始字符串。如果要在正则表达式上拆分,必须使用the ^{Try it online!
我删除了内部循环,因为它只做乘法输出,并重命名了变量以避免名称隐藏内置项
您需要更改此部分:
所以结果是
相关问题 更多 >
编程相关推荐