简体   繁体   中英

Python Finding if Item in list in another list

I want to see if an item in the list matches with another item in a seperate list.

I then want to print the matching items.

columns1= ['Dog', 'cat' , 'bird', 'fish']
columns2= ['Dog', 'CAT', 'bird', 'rat']

for col in columns1:
    if col.upper() in [x.upper() for x in columns2]:
        print(col, 'Matches with', )
    else:
        print(col, 'DOES NOT Match With Anything')

Current output:

Dog Matches with
cat Matches with
bird Matches with
fish DOES NOT Match With Anything

Desired output:

Dog Matches with Dog
cat Matches with CAT
bird Matches with bird
fish DOES NOT Match With Anything

I've tried using list_name.index(string_here) , but then it is case sensitive:

for col in columns1:
    if col.upper() in [x.upper() for x in columns2]:
        z = columns2.index(col)
        print(col, 'Matches with', columns2[z] )
    else:
        print(col, 'DOES NOT Match With')

output:
Dog Matches with Dog
ValueError: 'cat' is not in list

I could make a separate list that capitalizes everything in the lists, but I feel like that is cheating and with a very large dataset will create unnecessary performance hits.

What's the better way to solve this?

I think the performance hit is here that you search in a list . This is linear search which is O(n) . If you store the values in a dictionary . Then the average lookup time will be O(1) which is way faster. Furthermore the str.upper() will only be called once per item.

So you first prepare a dictionary:

lookup = {k.upper():k for k in columns2}

Next we can use:

for col in columns1:
    result = 
    if result :
        print(col, 'Matches with', result )
    else:
        print(col, 'DOES NOT Match With')

The lookup.get(..) method will lookup if col.upper() is in the dictionary (note that the keys in the dictionary are in uppercase as well). If it is in the dictionary result will be the corresponding original value of columns2 . If not None will be returned. We thus only have to check for None to know if the lookup was successful.

This generates:

Dog Matches with Dog
cat Matches with CAT
bird Matches with bird
fish DOES NOT Match With

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