简体   繁体   中英

Nested Python for loop only works with the last item in a list

I have encountered an issue where the 2nd for loop in a nested loop in Python only works for the last item in the list.

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)

As you can see in the code I am trying to loop through every item in the list and then in each loop of the loop before I want to append the string "TEST" to the end of the word that's currently looped through first loop.

Let's parse an input for example "aword, anotherword, yetanotherword, certainword" . I would expect the program to produce the following output "awordTEST, anotherwordTEST, yetanotherwordTEST, certainwordTEST" .

Instead this is the actual output "aword, anotherword, yetanotherword, certainwordTEST" .

I can't figure out why does the 2nd loop only work for the last item in the list.

Edit: suggested solution was to use a single for loop. The thing is that I need to work with that 2nd for loop later and it is important for it to be in that 2nd for loop. Thanks.

str.split does not accept regular expressions to split on. If you look at the contents of list , you'll see it's just the original string. If you want to split on a regex, you must use the re 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!

I removed the inner loop because it was doing nothing but multiplying outputs, and renamed variables to avoid name-shadowing built-ins.

you need change this section:

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

so the result is

awordTEST
anotherwordTEST
yetanotherwordTEST
certainwordTEST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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