我正在寻找一种简单(快速)的方法来确定两个无序列表是否包含相同的元素:
例如:
['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
我希望不用地图就能做到。
如果元素总是像示例中那样几乎排序,那么内置的
.sort()
(timsort)应该很快:如果不想就地排序,可以使用^{} 。
实际上,它可能总是比
collections.Counter()
快(尽管渐近O(n)
的时间比O(n*log(n))
的时间要好)。测量一下;如果重要的话。Python有一个用于无序(散列)事物集合的内置数据类型,称为
set
。如果将两个列表转换为集合,则比较将无序。Documentation on ^{}
编辑:@mdwhatcott指出要检查重复项。} :
set
忽略这些,因此您需要一个类似的数据结构,该结构还可以跟踪每个列表中的项数。这称为a multiset;标准库中的最佳近似值是a ^{从这里复制:Check if two unordered lists are equal
我认为这是这个问题最好的答案,因为
相关问题 更多 >
编程相关推荐