a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
A和b应该被认为是相等的,因为它们有完全相同的元素,只是顺序不同。
问题是,我的实际列表将由对象(我的类实例)组成,而不是整数。
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
A和b应该被认为是相等的,因为它们有完全相同的元素,只是顺序不同。
问题是,我的实际列表将由对象(我的类实例)组成,而不是整数。
当前回答
代入这个:
def lists_equal(l1: list, l2: list) -> bool:
"""
import collections
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
ref:
- https://stackoverflow.com/questions/9623114/check-if-two-unordered-lists-are-equal
- https://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets
"""
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
set_comp = set(l1) == set(l2) # removes duplicates, so returns true when not sometimes :(
multiset_comp = compare(l1, l2) # approximates multiset
return set_comp and multiset_comp #set_comp is gere in case the compare function doesn't work
其他回答
O(n): Counter()方法是最好的(如果你的对象是可哈希的):
def compare(s, t):
return Counter(s) == Counter(t)
O(n log n): sorted()方法是次优方法(如果你的对象是可排序的):
def compare(s, t):
return sorted(s) == sorted(t)
O(n * n):如果对象既不是可哈希的,也不是可排序的,你可以使用相等:
def compare(s, t):
t = list(t) # make a mutable copy
try:
for elem in s:
t.remove(elem)
except ValueError:
return False
return not t
我希望下面的代码可能在你的情况下工作:-
if ((len(a) == len(b)) and
(all(i in a for i in b))):
print 'True'
else:
print 'False'
这将确保两个列表a和b中的所有元素都是相同的,无论它们的顺序是否相同。
为了更好的理解,请参考我对这个问题的回答
代入这个:
def lists_equal(l1: list, l2: list) -> bool:
"""
import collections
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
ref:
- https://stackoverflow.com/questions/9623114/check-if-two-unordered-lists-are-equal
- https://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets
"""
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
set_comp = set(l1) == set(l2) # removes duplicates, so returns true when not sometimes :(
multiset_comp = compare(l1, l2) # approximates multiset
return set_comp and multiset_comp #set_comp is gere in case the compare function doesn't work
如果要在测试上下文中执行比较,则使用assertCountEqual(a, b) (py>=3.2)和assertItemsEqual(a, b) (2.7<=py<3.2)。
也适用于不可哈希对象的序列。
如果列表中包含不可哈希的项(比如对象列表),你可以使用Counter类和id()函数,比如:
from collections import Counter
...
if Counter(map(id,a)) == Counter(map(id,b)):
print("Lists a and b contain the same objects")