首页 > 解决方案 > python中的高效列表比较

问题描述

我想有效地比较两个列表并确定两者是否共享完全相同的元素。

列表可以是None、空的和各种长度的。列表中元素的顺序无关紧要,所以['a', 'b', 'c'] == ['a', 'c', 'b']在我的情况下是相等的。

我目前的解决方案如下所示:

 def list_a_equals_list_b(list_a, list_b):
    if list_a != None and list_b != None:
        if len(list_a) != len(list_b):
            return False
        else:
            return len(frozenset(list_a).intersection(list_b)) == len(list_a)
    elif list_a == None and list_b == None:
        return True
    else:
        return False

有没有更有效的方法来比较这些列表?

谢谢!

标签: pythonlistperformancecomparison

解决方案


如果您在任一列表中都没有重复项,则可以使用一组:

if listA == listB  \
or listA and listB \
   and len(listA) == len(listB) \
   and not set(listA).symmetric_difference(listB):
   # lists have the same elements
else:
   # there are differences

如果您确实允许重复,那么您可以使用集合中的计数器(如果您没有重复也可以使用)

from collections import Counter

if listA == listB  \
or listA and listB \
   and len(listA) == len(listB) \
   and Counter(listA)==Counter(listB):
   # lists have the same elements
else:
   # there are differences

推荐阅读