python - 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'])
解决方案
我想您的意思是list_1
并且list_2
在您的问题中是...列表,对吗?(正如你所拥有的那样,list_1
是 atuple
并且list_2
是dict
.
如果是这种情况,那么在声明列表时必须使用方括号[]
而不是括号。()
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'}]
推荐阅读
- c++ - 上下文依赖于 QListView 中的拖放
- python - re.findall 返回正确数量的匹配,但所有空字符串
- tensorflow - TensorFlow Serving 错误:'StatelessIf 设置了 '_lower_using_switch_merge' 属性,但不支持降低。'
- c++ - 如何在 TStringGrid 单元格中绘制按钮
- r - 为什么 dbClearResult() 需要这么长时间?
- css - 网格项目不尊重网格模板区域中的点表示法
- mongodb - 使用 CNAME 记录使用 mongoDB 地图集创建自定义域
- ansible - 如何使用 ansible-playbook --limit 与 IP 地址,而不是主机名?
- c# - 如何为 Visual Studio 中的所有项目创建全局文件?
- javascript - 相对于鼠标指针显示模态组件并正确定位模态组件