python - 比较python中两个列表中的元素
问题描述
我有两个列表如下:
a = ['abc','def', 'ghi'], b=['ZYX','WVU']
并想确认union
两个列表是否等于超集
c = ['ZYX', 'def', 'WVU', 'ghi', 'abc']
我试过以下:
>>> print (c == list(set(b).union(c)))
>>> False
任何人都可以展示我在这里缺少的东西吗?
解决方案
只需使用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))))
推荐阅读
- php - Angular 4:使用 PHP API 在数据库更改时自动刷新数据
- c++ - 如何在 Unreal Engine 4.20 中将项目“Unreal Studio”更改为 C++ 项目
- r - 在R中将yyyy数字数据转换为日期格式
- reactjs - 我一直在尝试使用 npx create-react-app 创建一个新的 react 项目,但出现错误
- django - 为什么在从 SQLite 集成到 PostgreSQL 后测试结果会有所不同并且不通过?
- java - 格里芬错误:java.lang.NoSuchMethodError
- kotlin - 我可以在 kotlin-js 中将 kotlinx.html 与文档一起使用吗?
- python-3.x - 需要在 selenium 中列出以通过 xpath 查找元素
- .htaccess - 如何在.htaccess中从文件夹重定向到图像而不更改url
- r - 使用 R 绘图的 Restyle Buttons 将颜色映射到变量上