简体   繁体   中英

Comparing items of case-insensitive list

So I have two lists, with items in varying cases. Some of the items are the same but are lowercase/uppercase. How can I create a loop to run through all the items and do something with each item, that also ignores what case the item may have?

fruits = ['Apple','banana','Kiwi','melon']
fruits_add = ['apple','Banana','KIWI','strawberry']

I want to create a loop that goes through each item in fruits_add and adds it to fruits , if the item is not already in fruits . However an item like 'apple' and 'Apple' need to count as the same item.

I understand how to convert individual items to different cases and how to check if one specific item is identical to another (disregarding case). I don't know how to create a loop that just does this for all items.

Found answers to similar questions for other languages, but not for Python 3.

My attempt:

for fruit.lower() in fruits_add:
    if fruit in fruits:
        print("already in list")

This gives me an error:

SyntaxError: can't assign to function call

I've also tried converting every item in each list to lowercase before comparing the lists, but that doesn't work either.

fruit.lower() in the for loop won't work as the error message implies, you can't assign to a function call..

What you could do is create an auxiliary structure ( set here) that holds the lowercase items of the existing fruits in fruits , and, append to fruits if a fruit.lower() in fruit_add isn't in the t set (containing the lowercase fruits from fruits ):

t = {i.lower() for i in fruits}
for fruit in fruits_add:
    if fruit.lower() not in t:
        fruits.append(fruit)

With fruits now being:

print(fruits)
['Apple', 'banana', 'Kiwi', 'melon', 'strawberry']

I wouldn't use the lower() function there. Use lower like this:

for fruit in fruits_add:
    if fruit.lower() in fruits:
        print("already in 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