python - 循环遍历 2 个字典列表
问题描述
我有这 2 个字典列表,如果list1
在list2
.
list1=[{'name':'A','color':'1'},
{'name':'B','color':'2'}]
list2=[{'name':'A','color':'3'},
{'name':'C','color':'1'}]
for item in list1:
for ii in list2:
if item['name'] != ii['name']:
print item['name']
我得到的输出是
A
B
B
我希望它能够打印B
,因为 list2 中没有 b。不知道我做错了什么......任何帮助将不胜感激。
谢谢
解决方案
目前在您的双 for 循环中,您打印list1 和 list2 的两个元素item['name']
之间的不匹配any
,这不是您想要的。
相反,您可以将两个列表中的名称转换为集合并获取集合差异
list1=[{'name':'A','color':'1'},
{'name':'B','color':'2'}]
list2=[{'name':'A','color':'3'},
{'name':'C','color':'1'}]
#Iterate through both lists and convert the names to a set in both lists
set1 = {item['name'] for item in list1}
set2 = {item['name'] for item in list2}
#Take the set difference to find items in list1 not in list2
output = set1 - set2
print(output)
输出将是
{'B'}
推荐阅读
- windows - 函数调用后 ESI 和 EDI 改变值
- r - 在推荐实验室中使用用户 ID 进行预测
- flutter-layout - 主页背景和导航栏抖动
- javascript - 从 figcaption 获取 Imagelightbox 中 Ligthbox 的标题
- proxy - Nuxt Axios 动态网址
- android - Intent.createChooser 的 startActivity 中的 Android(共享按钮)崩溃适用于除像素外的大多数手机
- appium - UIAutomatorViewer 显示相同的资源 id
- java - Spring boot RestTemplate 发布 400 错误
- spring-cloud-config - 带有本机文件的弹簧云配置
- total.js - total.js 应用程序扩展能力