Skip to main content
 首页 » 编程设计

python之查找列表中的事件

2025年05月04日12Renyi-Fan

我正在尝试查找列表中每个索引的最大出现次数。例如,如果索引 0 中的事件有 5 次“find”,则记录 5,如果索引 1 有 2 次“find”,则记录 2。因此对于索引 0 和索引 1 都将得到 5 和 2。

a = [{'test': []},  
     {'test': [{'testing': 'Not', 'Nottesting': 'Yes'}]}, 
     {'test': [{'testing': 'find', 'Nottesting': 'yes'}]}, 
     {'test': [{'testing': 'maybe', 'Nottesting': 'yes'}, 
               {'testing': 'find', 'Nottesting': 'maybe'}, 
               {'testing': 'find', 'Nottesting': 'haha'}, 
               {'testing': 'find', 'Nottesting': 'sometimes'}, 
               {'testing': 'sowell', 'Nottesting': 'some'}]}, 
     {}, 
     {}] 

有没有办法根据每个列表的最大值打印计数?

aa = [] 
for index, l in enumerate(a): 
    count = 0 
    find = [] 
    for trying in l.get("test", []): 
        if trying["testing"] == "find": 
            count += 1 
            print(count) 

我尝试使用建议的方法但无济于事。

我当前的输出:

1 
1 
2 
3 

预期输出

1 
3 

请您参考如下方法:

只需向后缩进打印指令,这样它只会在嵌套循环之后执行,而不是在每次出现时都执行。

for index, l in enumerate(a): 
    count = 0 
    find = [] 
 
    for trying in l.get("test", []): 
        if trying["testing"] == "find": 
            count += 1 
 
    if count : print(count)