[英]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.