Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python遍历嵌套列表以检查元素是否出现超过3次_Python_List_Iteration_Nested Loops - Fatal编程技术网

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

Python遍历嵌套列表以检查元素是否出现超过3次,python,list,iteration,nested-loops,Python,List,Iteration,Nested Loops,我有两个Python列表 列表1是一个集合,因此只有唯一的元素:['bird','elephant','123','test..,'hi'] 列表2是一个嵌套列表:[['bird'、'123',43']、[''、'bird'、'33]、'123'、'hello'、'bird'] 我想检查列表1中的元素是否在嵌套列表中的任何位置出现3次以上。如果它出现3次或更多次,我想从嵌套列表中删除该元素 在上面所示的示例中,应该从所有3个嵌套列表中的列表2中删除元素'bird'。我想要的输出是:[['123'

我有两个Python列表

列表1是一个集合,因此只有唯一的元素:
['bird','elephant','123','test..,'hi']

列表2是一个嵌套列表:
[['bird'、'123',43']、[''、'bird'、'33]、'123'、'hello'、'bird']

我想检查列表1中的元素是否在嵌套列表中的任何位置出现3次以上。如果它出现3次或更多次,我想从嵌套列表中删除该元素

在上面所示的示例中,应该从所有3个嵌套列表中的列表2中删除元素
'bird'
。我想要的输出是:
[['123',43'],['','33],'123','hello']
,我还想创建一个单独的删除项目列表


请有人分享一下我是如何做到这一点的?

您需要对元素进行计数,以了解项目是否出现三次以上。为了提高效率,您应该避免在循环中使用
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']]
从集合导入计数器
来自itertools进口链
s=集合(['bird'、'elephant'、''123'、'test'、'hi']))
列表2=['bird'、'123'、'43']、[''bird'、'33']、['123'、'hello'、'bird']
#获取s和列表2中所有项目的计数
计数=计数器(链中的字对字。如果是s中的字,则从_iterable(列表2)开始)
#按计数<3创建列表过滤器
newList=[[item for item for sublist if counts.get(item,0)<3]for sublist in list2]
#[['123',43'],[''33'],['123',你好]]

您当前的代码是什么?你试过什么?我试过这个:
对于列表1中的I:对于列表2中的j:if j.count(I)==3:del(j)
@RomanPerekhrest“超过3次”不是
==3
。请澄清您的条件。请明确我的目的,谢谢@MarkMeyer,我不知道itertools模块,因此这很方便了解。我怎么知道集合中的哪个单词被发现了3次以上?我想把它们添加到列表中吗?我确实删除了“remove.append(item)”,但这返回了数字。谢谢大家!@上述代码中的q21311计数类似于字典:
计数器({'bird':3,'123':2,':1})
,因此您可以遍历它来查找>=3的值。类似于:
[key for key,value in counts.items(),如果value>=3]