Home > Mobile >  Nested loops in Python with two list
Nested loops in Python with two list

Time:08-22

Why my loop not return first values? I want replaces specific text if this text exist in my value, but if not exist, i want get a initial meaning. In last value I get that i need, but first value my code miss.

    p = ["Adams","Tonny","Darjus FC", "Marcus FC", "Jessie AFC", "John CF", "Miler 
    SV","Redgard"]
    o = [' FC'," CF"," SSV"," SV"," CM", " AFC"]
    for i, j in itertools.product(p, o):
        if j in i:
            name = i.replace(f"{j}","")
            print(name)
        elif j not in i:
            pass        
    print(i)

I got this:

    Darjus
    Marcus
    Jessie
    John
    Miler
    Redgard

but i want this:

    Adams
    Tonny
    Darjus
    Marcus
    Jessie
    John
    Miler
    Redgard

CodePudding user response:

The use of product() is going to make solving this problem a lot harder than it needs to be. It would be easier to use a nested loop.

p = ["Adams", "Tonny", "Darjus FC", "Marcus FC",
     "Jessie AFC", "John CF", "Miler SV", "Redgard"]
o = [' FC', " CF", " SSV", " SV", " CM", " AFC"]

for i in p:
    # Store name, for if no match found
    name = i
    for j in o:
        if j in i:
            # Reformat name if match
            name = i.replace(j, "")
    print(name)
  • Related