首页 > 解决方案 > 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']]我还想创建一个单独的已删除项目列表。

请有人分享我如何解决这个问题?

标签: pythonlistiterationnested-loops

解决方案


您将不得不计算元素以了解项目是否出现超过 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']]

推荐阅读