[英]Loop through 2 list of dictionaries
我有这2个字典列表,如果在list2
找不到它们,我试图从list1
打印出所有名称 s。
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。 不知道我在做什么错...任何帮助将不胜感激。
谢谢
当前,在double for循环中,您打印item['name']
以获得list1和list2的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'}
(显然)这不是代码的逻辑。 您可以通过名字的所有组合遍历,并打印从一个list1
,每次它不符合任何名称list2
。
相反,请不要打印它,直到您知道所有这些名称都不匹配:
for item in list1:
found = False
for ii in list2:
if item['name'] == ii['name']:
found = True
if not found:
print item['name']
这是对您的实现的直接更改。 有一行可以使用理解力, all
和其他Python功能来做到这一点。
您遍历并在找不到匹配项的所有情况下进行打印。
您可以在更有效的集合中使用查找:
for x in list1:
if x['name'] not in {y['name'] for y in list2}:
print(x['name'])
使用all()
,您可以执行以下操作:
for x in list1:
if all(x['name'] != y['name'] for y in list2):
print(x['name'])
如果名称在list1中是唯一的,则可以使用一组:
list1=[{'name':'A','color':'1'},
{'name':'B','color':'2'}]
list2=[{'name':'A','color':'3'},
{'name':'C','color':'1'}]
set1 = set(d['name'] for d in list1)
missingNames = set1.difference(d['name'] for d in list2) # {'B'}
如果它们不是唯一的,并且您要匹配实例数,则可以使用来自集合的Counter来做到这一点:
from collections import Counter
count1 = Counter(d['name'] for d in list1)
count2 = Counter(d['name'] for d in list2)
missingNames = list((count1-count2).elements()) # ['B']
使用Counter时,如果列表1中有两个名称为“ A”的条目,则输出将为['A','B'],因为列表1中只有两个“ A”之一会在列表2中找到匹配项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.