检查两个无序列表是否相等 [英] Check if two unordered lists are equal

查看:128
本文介绍了检查两个无序列表是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for an easy (and quick) way to determine if two unordered lists contain the same elements:

例如:

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

我希望不使用地图就可以做到这一点.

I'm hoping to do this without using a map.

推荐答案

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

Python has a built-in datatype for an unordered collection of (hashable) things, called a set. If you convert both lists to sets, the comparison will be unordered.

set(x) == set(y)

set

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

@mdwhatcott points out that you want to check for duplicates. set ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a 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
>>> 

这篇关于检查两个无序列表是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆