Nested loops in Python with two list

Question:

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
Asked By: Darjus Vasiukevic

||

Answers:

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)
Answered By: drewburr

If you would like to store the names in a list, here’s one way to do it:

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

for name in p:
    if name.split()[-1] in o:
        result.append(name.split()[0])
    else:
        result.append(name)
print(result)

['Adams', 'Tonny', 'Darjus', 'Marcus', 'Jessie', 'John', 'Miler', 'Redgard']
Answered By: Gold79
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.