问题
I have 2 lists. The first is list_A = ['Sasi', 'Babu', 'kuttapppan', 'mathayi']
and my second list is list_B = ['Raman', 'Kesavan', 'sasi', 'unni', 'Kuttappan']
.
I want to compare these two lists and identify the values which are duplicated in the second list regardless of if it starts with a capital letter or a lowercase letter. I've tried the following method:
if not [name for name in list_A if name in list_B]:
print name
But it is not working as expected.
回答1:
#Might be better if we are dealing with huge lists.
list_A = ['Sasi', 'Babu', 'kuttapppan', 'mathayi']
list_B = ['Raman', 'Kesavan', 'sasi', 'unni', 'Kuttappan'].
d = [x.lower() for x in list_A] # make dict of list with less elements
for m in list_B: # search against bigger list
if m.lower() in d: print(m)
回答2:
Try using sets. The difference set operation will return unique elements to set abc in the following example. Common elements can be obtained using the intersection set operation
abc = [i.lower() for i in ["a","b","c"]]
bcd = [i.lower() for i in ["b","c","d"]]
print set(abc).difference(set(bcd))
print set(abc).intersection(set(bcd))
回答3:
First, convert each element in each list
to lowercase with lower()
. Then, the easiest way to compare duplicates is with set
operations. You can combine these steps with a set
comprehension:
list_A = ['Sasi', 'Babu', 'kuttapppan', 'mathayi']
list_B = ['Raman', 'Kesavan', 'sasi', 'unni', 'Kuttappan']
list_A = {item.lower() for item in list_A}
list_B = {item.lower() for item in list_B}
Then use intersection of set
s:
copies = list_A & list_B
回答4:
Actually you can make this in just one list comprehansion:
list_A = ['Sasi', 'Babu', 'kuttappan', 'mathayi']
list_B = ['Raman', 'Kesavan', 'sasi', 'unni', 'Kuttappan', 'SaSi']
duplicated = [B for B in list_B if B.lower() in (x.lower() for x in list_A)]
print(duplicated)
This way it returns the original values while comparing the lowercased. Using sets will return the lowercased values and will delete all duplicated values in list_B.
来源:https://stackoverflow.com/questions/33643757/case-insensitive-comparison-of-two-lists