通过一个或多个属性比较两个无序列表的最有效方法是什么?我很想知道是否存在一种Python方式来查找列表A中的每个项目是否存在列表B中的项目,其中列表A中的项目与列表B中的项目在指定属性中匹配。
在我的示例案例中,我在单元测试中有两个.zip文件,并且想测试文件是否匹配,但是我确实在为我的个人工具集寻找一个好的通用解决方案。这是我的第一次尝试:
with ZipFile('A.zip') as old:
with ZipFile('B.zip') as new:
oldFileInfo = old.infolist()
allFound = True
for info in new.infolist():
matches = [item for item in oldFileInfo if item.CRC == info.CRC and \
basename(item.filename) == basename(info.filename) ]
if len(matches) == 0:
allFound = False
break
也许这是微不足道的,但是我还没有找到一种好的方法。
迈克尔的问候
这很容易,您应该使用集合:
if set(list1).difference(set(list2)):
# lists are different
# different_items = set(list1).difference(set(list2))
pass
else:
# lists are the same
pass
您可以将结构转换为可迭代项或列表:
list1 = [(i.CRC, basename(i.filename)) for i in old.infolist()]
list2 = [(i.CRC, basename(i.filename)) for i in new.infolist()]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句