我正在尝试查找列表中每个索引的最大出现次数。例如,如果索引0中的出现次数是“查找”的5倍,则记录5,而如果索引1中的事件是“查找”的2倍,则记录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
答案 0 :(得分:2)
只需向后缩进打印指令,以使其仅在嵌套循环之后执行,而不是在每次出现时都执行。
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)
答案 1 :(得分: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
if count != 0:
print(count)
答案 2 :(得分:2)
单线:
print([sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a if sum([1 for x in i.get('test',[]) if x['testing']=='find'])!=0])
输出:
[1, 3]
或两层(更易读):
l=[sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a]
print(list(filter(None,l)))
输出:
[1, 3]