首页 > 解决方案 > 比较python中两个列表中的元素

问题描述

我有两个列表如下:

a = ['abc','def', 'ghi'], b=['ZYX','WVU']

并想确认union两个列表是否等于超集

c = ['ZYX', 'def', 'WVU', 'ghi', 'abc'] 

我试过以下:

>>> print (c == list(set(b).union(c)))
>>> False

任何人都可以展示我在这里缺少的东西吗?

标签: pythonlistsetset-union

解决方案


只需使用set方法,因为列表中的项目顺序不同,这就是您收到False结果的原因。

print (set(c) == set(list(set(b).union(c))))

另一种解决方案是使用Counter类。该Counter方法对于大列表应该更有效,因为它具有线性时间复杂度(即 O(n))

from collections import Counter
Counter(c) == Counter(list(set(b).union(c))))

推荐阅读