Python 两个列表之间的多重条件

标签 python list dictionary

我正在使用 python 3,我需要检查不同列表中的 3 个变量。如果 username age lang 与其他列表不同,我想打印数据

这是我的代码:

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

如何避免循环中出现重复数据?还有另一种方法可以做我想做的事而不是使用双循环?

最佳答案

您可以使用 set 对一个列表中的一系列 tuple 元素进行哈希处理。当名称位于 list2 中时,下面的逻辑特别有效,可以采用 name-aname-b 等格式,并且您只需对第一部分感兴趣。

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 两个列表之间的多重条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52834594/

相关文章:

python - 同时在python中运行多个服务器(线程)

list - F# 遍历不同类型的列表

html - 以特殊顺序制作网格元素列表。 (例如,使用 flex-box 等)

python - 通过迭代给定数据返回字典列表

python - 更改 csv.DictReader 类型中字典键的值

javascript - 如何在打开连接时从 Javascript 发送一些附加数据,例如用户名或时间?

python - Matplotlib 动画 : first frame remains in canvas when using blit

r - 在r中的ggplot中添加 map 中心点

相当于 python 字符串切片的 JavaScript

java - Spring返回List的正确方法是什么