两个列表之间的Python多重条件 [英] Python multiple condition between two list
问题描述
我正在使用python 3,我需要检查其他列表中的3个变量.如果username
age
lang
与其他列表不同,我想打印数据
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
这是我的代码:
list1 = []
list2 = []
list1.append({'username' : 'alice', 'age' : 25, 'lang' : 'IT'})
list1.append({'username' : 'carole', 'age' : 40, 'lang' : 'FR'})
list1.append({'username' : 'john', 'age' : 30, 'lang' : 'FR'})
list1.append({'username' : 'mick', 'age' : 20, 'lang' : 'US'})
list1.append({'username' : 'mick', 'age' : 30, 'lang' : 'US'})
list2.append({'username' : 'mick-c', 'age' : 30, 'lang' : 'US'})
list2.append({'username' : 'john', 'age' : 30, 'lang' : 'FR'})
list2.append({'username' : 'john-b', 'age' : 30, 'lang' : 'FR'})
for l1 in list1:
username = l1['username']
age = l1['age']
lang = l1['lang']
for l2 in list2:
if username not in l2['username'] and l2['age'] != age and l2['lang'] != lang:
print(str(username) + ' ' + str(age) + ' ' + str(lang))
输出:
alice 25 IT
alice 25 IT
alice 25 IT
carole 40 FR
mick 20 US
mick 20 US
我的预期输出是:
alice 25 IT
carole 40 FR
mick 20 US
如何避免循环中没有重复数据?还有另一种方法可以执行我想要的操作,而不是使用双循环吗?
How can I do to not have duplicated data in the loop ? And there is another way to do what I want instead of use double loops ?
推荐答案
您可以使用set
对一个列表中的tuple
元素序列进行哈希处理.当名称以list2
开头时,下面的逻辑特别有用,格式可以为name-a
,name-b
等,并且您只对第一部分感兴趣.
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
这篇关于两个列表之间的Python多重条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!