python - Python遍历嵌套列表以检查元素是否出现超过3次
问题描述
我在 Python 中有 2 个列表。
清单 1 是一个集合,因此只有唯一的元素:['bird','elephant,'','123','test..,'hi']
列表 2 是一个嵌套列表:[['bird','123',43'],['','bird','33],['123','hello','bird']]
我想检查列表 1 中的元素是否在嵌套列表中的任何位置出现超过 3 次。如果它确实出现 3 次或更多次,我想从嵌套列表中删除此元素。
在上面显示的示例中,该元素'bird'
应从列表 2 中删除,从所有 3 个嵌套列表中删除。我之后的输出是:[['123',43'],['','33],['123','hello']]
我还想创建一个单独的已删除项目列表。
请有人分享我如何解决这个问题?
解决方案
您将不得不计算元素以了解项目是否出现超过 3 次。为了提高效率,您应该避免count()
在循环中使用并且只执行一次。
一旦有了计数,您就可以使用以下内容过滤您的列表:
from collections import Counter
from itertools import chain
s = set(['bird','elephant','','123','test','hi'])
list2 = [['bird','123','43'],['','bird','33'],['123','hello','bird']]
# get counts of all the items that are in s and list2
counts = Counter(word for word in chain.from_iterable(list2) if word in s)
# create lists filter by count < 3
newList = [[item for item in sublist if counts.get(item, 0) < 3] for sublist in list2]
# [['123', '43'], ['', '33'], ['123', 'hello']]
推荐阅读
- git - Git push to origin master 似乎成功但没有任何变化
- performance - webgl中的什么命令导致纹理内存被处理
- amazon-s3 - 将实时视频从 Raspberry Pi 摄像头流式传输到 Android 应用程序
- hyperledger-fabric - HL Fabric - 织物安装*没有*织物样品?
- node.js - “需要登录”错误。使用 Google API 获取 oauth2 令牌后如何登录
- reactjs - 如何使用 create-react-app 用 AdonisJS 实现 ReactJS?
- javascript - 如何根据属性值过滤 MapBox 热图中的点?
- java - 为什么所有分区都没有分配给正在运行的单个 KafkaConsumer?
- spring - 如何修复这些警告消息——com.couchbase.client.deps.io.netty.util.IllegalReferenceCountException: refCnt: 0, increment: 1
- html - HtmlCleaner 不处理字符引用