python 中的高效列表比较
Efficient list comparison in 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
是否有更有效的方法来比较这些列表?
谢谢!
如果您在两个列表中都没有重复项,您可以使用集合:
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
如果您的对象是可散列的,则 Counter() 方法是最好的。
但这里的 sorted() 内置函数是您最好的选择。
def list_a_equals_list_b(list_a, list_b):
return (list_a == None and list_b == None) or sorted(list_a) == sorted(list_b)
我想有效地比较两个列表并确定它们是否共享完全相同的元素。
列表可以是 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
是否有更有效的方法来比较这些列表?
谢谢!
如果您在两个列表中都没有重复项,您可以使用集合:
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
如果您的对象是可散列的,则 Counter() 方法是最好的。 但这里的 sorted() 内置函数是您最好的选择。
def list_a_equals_list_b(list_a, list_b):
return (list_a == None and list_b == None) or sorted(list_a) == sorted(list_b)