我正在寻找一个简单(快速)的方法来确定两个无序列表是否包含相同的元素:

例如:

['one', 'two', 'three'] == ['one', 'two', 'three'] :  true
['one', 'two', 'three'] == ['one', 'three', 'two'] :  true
['one', 'two', 'three'] == ['one', 'two', 'three', 'three'] :  false
['one', 'two', 'three'] == ['one', 'two', 'three', 'four'] :  false
['one', 'two', 'three'] == ['one', 'two', 'four'] :  false
['one', 'two', 'three'] == ['one'] :  false

我希望不用地图就能做到。


当前回答

如果你不想使用集合库,你可以这样做: 假设a和b是你的列表,下面返回匹配元素的数量(它考虑顺序)。

sum([1 for i,j in zip(a,b) if i==j])

因此,

len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])

如果两个列表相同,包含相同的元素并且顺序相同,则为True。否则错误。

因此,您可以像上面的第一个响应一样定义compare函数,但不包含collections库。

compare = lambda a,b: len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])

and

>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3], [1,2,4])
False

其他回答

假设您已经知道列表的大小相等,当且仅当两个向量完全相同(包括顺序)时,下面的语句将保证为True

functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)

例子:

>>> from functools import reduce
>>> def compvecs(a,b):
...     return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
... 
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>> 

获取列表的字符串表示形式并比较它们怎么样?

>>> l1 = ['one', 'two', 'three']
>>> l2 = ['one', 'two', 'three']
>>> l3 = ['one', 'three', 'two']
>>> print str(l1) == str(l2)
True
>>> print str(l1) == str(l3)
False

如果你不想使用集合库,你可以这样做: 假设a和b是你的列表,下面返回匹配元素的数量(它考虑顺序)。

sum([1 for i,j in zip(a,b) if i==j])

因此,

len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])

如果两个列表相同,包含相同的元素并且顺序相同,则为True。否则错误。

因此,您可以像上面的第一个响应一样定义compare函数,但不包含collections库。

compare = lambda a,b: len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])

and

>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3], [1,2,4])
False

如果元素总是像你的例子中那样几乎排序,那么内置的.sort() (timsort)应该很快:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

如果你不想在某个位置排序,你可以使用sorted()。

在实践中,它可能总是比collections.Counter()更快(尽管对于.sort(),渐进地O(n)时间比O(n*log(n))时间更好)。测量;如果这很重要的话。

sorted(x) == sorted(y)

从这里复制:检查两个无序列表是否相等

我认为这是这个问题最好的答案,因为

这比在这个答案中使用counter要好 x.sort()对x进行排序,这是一个副作用。Sorted (x)返回一个新列表。