Python Multiple Condition Between Two List
I'm using python 3 and I need to check 3 variables in different list. I want to print data if username age lang are different from the other list Here is my code : list1 = [] list2
Solution 1:
You can use set
to hash a sequence of tuple
elements from one list. The logic below works specifically when names are in list2
can be of the format name-a
, name-b
, etc, and you are only interested in the first part.
from operator import itemgetter
def field_getter(x):
i, j, k = itemgetter('username', 'age', 'lang')(x)
return i.split('-')[0], j, k
item_set = set(map(field_getter, list2))
for d in list1:
d_fields = field_getter(d)
if field_getter(d) not in item_set:
print(*d_fields)
alice 25 IT
carole 40 FR
mick 20 US
Solution 2:
You should output the record only if it's not found in list2
, so you should use the for-else
construct to print
after you've made sure there's no entry in list2
with all 3 fields passing the equality tests (rather than inequality tests):
for l1 in list1:
username = l1['username']
age = l1['age']
lang = l1['lang']
for l2 in list2:
if username in l2['username'] and l2['age'] == age and l2['lang'] == lang:
breakelse:
print(str(username) + ' ' + str(age) + ' ' + str(lang))
This outputs:
alice 25 IT
carole 40 FR
mick 20 US
Solution 3:
Sort the items with a comparison rule on the three fields. The identical records will appear next to each other and a single loop will be enough.
Post a Comment for "Python Multiple Condition Between Two List"