简体   繁体   English

不区分大小写的列表的比较项目

[英]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 . 我想创建一个循环,遍历fruits_add每个项目并将其添加到fruits (如果该项目尚未在fruits However an item like 'apple' and 'Apple' need to count as the same item. 但是,像'apple''Apple'这样的项目需要算作同一项目。

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. 找到了其他语言(而非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.. for循环中的fruit.lower()不会像错误消息所暗示的那样起作用,您不能将其分配给函数调用。

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 ): 你可以做的是建立一个辅助结构( set在这里),它保存在现有成果的小写项目fruits ,并appendfruits如果fruit.lower()fruit_add不在t集(包含小写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: 现在有fruits

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

I wouldn't use the lower() function there. 我不会在那里使用Lower()函数。 Use lower like this: 像这样使用低一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM