我需要比较两个列表,但不考虑它们的顺序:
list_a = ['one', 'two', 'three']
list_b = ['three', 'one', 'two']
当我尝试比较它们时,它返回False
:
>>> list_a == list_b
False
两个列表都有很多元素,最优的比较方法是什么?
我需要比较两个列表,但不考虑它们的顺序:
list_a = ['one', 'two', 'three']
list_b = ['three', 'one', 'two']
当我尝试比较它们时,它返回False
:
>>> list_a == list_b
False
两个列表都有很多元素,最优的比较方法是什么?
你需要比较两个列表的 Counter
是否相同。
>>> from collections import Counter
>>> list_a = ['one', 'two', 'three']
>>> list_b = ['three', 'one', 'two']
>>> Counter(list_a) == Counter(list_b)
True
>>> list_b = ['three', 'one', 'two', 'two']
>>> Counter(list_a) == Counter(list_b)
False
>>> set(list_a) == set(list_b)
True # False positive
另一个解决方案是对两个列表进行排序,然后进行比较。在处理大型列表时,Counter
方法应该更加高效,因为它具有线性时间复杂度(即O(n)),而排序只有伪线性时间复杂度(即O(n*log(n)))。
set
。>>> list_a = ['one', 'two', 'three']
>>> list_b = ['three', 'one', 'two']
>>> set(list_a) == set(list_b)
True
>>> sorted(list_a) == sorted(list_b)
True
list_a = ["a", "a", b"] ; list_b = ["a", "b", "b"] ; set(list_a) == set(list_b) # True
- Glutexocollections
模块中的 Counter
将是解决问题的方法。由于您有字符串并且如答案所示:
from collections import Counter
.....
if Counter(list_a) == Counter(list_b): # True or False
...
if Counter(map(id,list_a)) == Counter(map(id,list_b)):
print "same unhashable things in list_a and list_b"