簡體   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