繁体   English   中英

Pythonic方法按属性比较两个无序列表

[英]Pythonic Way to compare two unordered lists by attributes

通过一个或多个属性比较两个无序列表的最pythonic方法是什么? 我想知道是否有一种pythonic方法来查明列表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

您可以将结构转换为iterables或lists:

list1 = [(i.CRC, basename(i.filename)) for i in old.infolist()]
list2 = [(i.CRC, basename(i.filename)) for i in new.infolist()]

一种可能的方法是:

def areEqual(old, new):
    set1 = set((x.attribute1, x.attribute2) for x in old)
    set2 = set((x.attribute1, x.attribute2) for x in new)

    return set1 == set2

您可以使用旧列表和新列表创建集合,然后比较它们:

old_set = set((item.CRC, item.filename) for item in old_info)
new_set = set((item.CRC, item.filename) for item in new_info)

all_match = new_set.issubset(old_set)  # or old_set.issuperset(new_set)

您可以从排序列表开始。 它只有n log n的bigO然后你可以逐个比较元素,如果找到一对不匹配则停止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM