如何比较两个不同顺序的列表?

时间:2017-09-06 18:30:06

标签: python

我需要比较两个列表而不考虑他们的顺序:

list_a = ['one', 'two', 'three']
list_b = ['three', 'one', 'two']

当我尝试比较它们时,它返回False

>>> list_a == list_b
False

两个列表都有很多元素,比较它们的最佳方法是什么?

3 个答案:

答案 0 :(得分:8)

您需要比较两个列表是否产生相同的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))。

答案 1 :(得分:7)

一种方法是比较每个列表的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

答案 2 :(得分:1)

Counter模块集合将是最佳选择。因为你有字符串,并在答案中显示:

from collections import Counter
.....
if Counter(list_a) == Counter(list_b): # True or False

如果列表中有任何不可用的元素(字符串和数字除外),如对象等,您可能想要取出他们的id并制作另一个列表并比较他们的Counter。

...
if Counter(map(id,list_a)) == Counter(map(id,list_b)):
    print "same unhashable things in list_a and list_b"