python - 检查两个无序列表是否相等

标签 python list comparison

<分区>

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

例如:

['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

我希望在不使用 map 的情况下做到这一点。

最佳答案

Python 有一个内置的数据类型,用于(可散列的)事物的无序集合,称为 set。如果将两个列表都转换为集合,则比较将是无序的。

set(x) == set(y)

Documentation on set


编辑:@mdwhatcott 指出您想检查重复项。 set 会忽略这些,因此您需要一个类似的数据结构来跟踪每个列表中的项目数。这称为 multiset ;标准库中最好的近似值是 collections.Counter :

>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>> 
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>> 

关于python - 检查两个无序列表是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46436502/

相关文章:

python - 持续运行的 worker 池

Python 在新行打印语句

C# 不使用额外内存的对象顺序列表

java - Wav 比较,相同的文件

PHP比较数组

javascript - 为什么 true * true === 1 在 JS 中?

python - 如何在 VSCode Jupyter Notebook 中拆分单元格?

python - 如何创建 Python stub 文件以及放置在哪里?

java - 将 Arrays.asList 与 int 数组一起使用

python - 如何创建多个列表?