Python 遍历嵌套列表以检查元素是否出现超过 3 次

Python iterating through a nested list to check if the element appears more than 3 times

我在 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']]