简体   繁体   中英

For loop in python to check elements in list

I have this code:

keys = ['well done','come on','going to','c','D','m','l','o']
values = ['well','going','come','D']
category = []
for index, i in enumerate(keys):
    for j in values:
        if j in i:
            category.append(j)
            break
        if index == len(category):
            category.append("other")
print(category)

I am getting this output ['well', 'other', 'come', 'going', 'other', 'D', 'other', 'other']

The expected output is ['well', 'come', 'going', 'other', 'D', 'other','other' 'other']

I'm not sure what's wrong with the code.

Any help would be appreciated.

Based on the updated questions, it's hard to tell if the first word in each key element will be the word in values. This example is too broad so I've taken that into account and updated my answer.

category = []
keys = ['start', 'steak well done', 'come on', 'He is going', 'c', 'D', 'm', 'l', 'o']
values = ['well', 'going', 'come', 'D']

for key in keys:
    if ' ' in key:
        for value in values:
            if value in key:
                category.append(value)
        continue
    if key in values:
        category.append (key)
        continue
    else:
        category.append ('other')

category
['other', 'well', 'come', 'going', 'other', 'D', 'other', 'other', 'other']

I would solve this issue with a flag that would mark if it was found.

Keep in mind that I switched between the names of your keys and values lists for it to fit better logically and changed the 'i' and 'j' for a better meaning for the names.

You can keep your names if you want and only add the two lines regarding 'found'.

values = ['well done', 'come on', 'going to', 'c', 'D', 'm', 'l', 'o']
keys = ['well', 'going', 'come', 'D']
category = []
for index, value in enumerate(values):
    found = False
    for key in keys:
        if key in value:
            category.append(key)
            found = True
            break
    if not found:
        category.append("other")
print(category)

Option 2:

values = ['well done', 'come on', 'going to', 'c', 'D', 'm', 'l', 'o']
keys = ['well', 'going', 'come', 'D']
category = []
for index, value in enumerate(values):
    for key in keys:
        if key in value:
            category.append(key)
            break
    else:
        category.append("other")
print(category)

Option 2 is a more elegant way for the solution in my opinion. else following a for will trigger in case a for loop finishes without hitting a break on the way.

Prints: ['well', 'come', 'going', 'other', 'D', 'other', 'other', 'other']

Regarding what you were doing wrong - You were adding the 'other' while going through your keys list rather than through your 'values' list.

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