Reputation: 71
I have this code and want to compare two lists.
list2= [('Tom','100'),('Alex','200')]
list3= [('tom','100'),('alex','200')]
non_match = []
for line in list2:
if line not in list3:
non_match.append(line)
print(non_match)
The results will be:
[('Tom', '100'), ('Alex', '200')]
because of case sensitivity! is there any way to avoid the case sensitivity in this case? I don't want to change the lists to upper or lower case.
Or any other method which can match these lists?
Upvotes: 2
Views: 2586
Reputation: 71
This worked for me! Both lists will be converted to lower case.
list2= [('Tom','100'),('Alex','200'),('Tom', '13285')]
list3= [('tom','100'),('ALex','200'),('Tom', '13285')]
def make_canonical(line):
name, number = line
return (name.lower(), number)
list22 = []
for line2 in list2:
search = make_canonical(line2)
list22.append(search)
list33 =[]
for line3 in list3:
search1 = make_canonical(line3)
list33.append(search1)
non_match = []
for line in list22:
if line not in list33:
non_match.append(line)
print(non_match)
Upvotes: 0
Reputation: 51643
You can make the comparison even more generic mixing int
s and whitespaces in the game by creating two dicts from your tuple-lists and compare the lists:
def unify(v):
return str(v).lower().strip()
list2= [('Tom ','100'),(' AleX',200)]
list3= [('toM',100),('aLex ','200')]
d2 = {unify(k):unify(v) for k,v in list2} # create a dict
d3 = {unify(k):unify(v) for k,v in list3} # create another dict
print(d2 == d3) # dicts compare (key,value) wise
The applied methods will make strings from integers, strip whitespaces and then compare the dicts.
Output:
True
Upvotes: 0
Reputation: 569
Using lower to convert the tuple to lower case for comparison
list2= [('Tom','100'),('Alex','200')]
list3= [('tom','100'),('alex','200')]
non_match = []
for line in list2:
name, val = line
if (name.lower(), val) not in list3:
non_match.append(line)
print(non_match)
Upvotes: 3
Reputation: 5703
You need to iterate tuples also inside loop
for line2 in list2:
for line3 in list3:
if len(line3) == len(line2):
lenth = len(line3)
successCount = 0
match = False
for i in range(lenth):
result = line2[i].lower() == line3[i].lower()
if result == True:
successCount = successCount +1;
result = False
if successCount == lenth:
non_match.append(line2)
print(non_match)
enjoy.....
Upvotes: 0
Reputation: 21831
You can't avoid transforming your data to some case-insensitive format, at some point. What you can do is to avoid recreating the full lists:
def make_canonical(line):
name, number = line
return (name.lower(), number)
non_match = []
for line2 in list2:
search = make_canonical(line2)
for line3 in list3:
canonical = make_canonical(line3)
if search == canonical:
break
else:
# Did not hit the break
non_match.append(line3)
Upvotes: 0