首页 > 解决方案 > Python:结合两个共同价值的字典列表

问题描述

我有两个字典列表。我希望工会基于

list_1 = ({'foo': 'bar', 'ip': '1.2.3.4'}, {'foo': 'bar2', 'ip': '2.3.4.5'})
list_2 = ({'foo': 'bar3', 'ip': '1.2.3.4'})

#calculated
list_3 should be: ({'foo': 'bar3', 'ip': '1.2.3.4'})

我正在努力:

tmplist = list(item['ip'] for item in list_1
                   if item['ip'] in list_2)

编辑:我有嵌套的 for 循环。有没有更蟒蛇的方式?

for item1 in list1:
        print(item1['ip_address'])
        for item2 in list2:
            if item1['ip_address'] == item2['ip_address']:
                print("Got a match: " + item1['foo'] + " == " +item2['foo'])

标签: python

解决方案


我想您的意思是list_1并且list_2在您的问题中是...列表,对吗?(正如你所拥有的那样,list_1是 atuple并且list_2dict.

如果是这种情况,那么在声明列表时必须使用方括号[]而不是括号。()

list_1 = [{'foo': 'bar', 'ip': '1.2.3.4'}, {'foo': 'bar2', 'ip': '2.3.4.5'}]
list_2 = [{'foo': 'bar3', 'ip': '1.2.3.4'}]

好的,假设你可以有这样的实现:

def matchings(iter1, iter2, selector):
    keys = {*map(selector, iter1)}
    return [*filter(lambda e: selector(e) in keys, iter2)]

并像这样使用它:

matchings(list_1, list_2, lambda e: e['ip'])
# [{'foo': 'bar3', 'ip': '1.2.3.4'}]

推荐阅读