Reputation: 147
I am trying to find the max occurrences for each index in the list. For example, if the occurences in Index 0 have 5 times "find" then 5 is recorded and if Index 1 has 2 times "find" then 2 is recorded. So for Both Index 0 and Index 1 will get 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)
I tried to use the method suggested but to no avail.
My current output:
1
1
2
3
Expected output
1
3
Upvotes: 1
Views: 86
Reputation: 71560
Or one-liner:
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])
Output:
[1, 3]
Or two-liner (more readable):
l=[sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a]
print(list(filter(None,l)))
Output:
[1, 3]
Upvotes: 2
Reputation: 1317
Just indent the printing directive backwards so that it would only be executed after the nested loop, not on every occurence.
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)
Upvotes: 2
Reputation: 1982
You are printing inside loop where you are increasing count. You need to print it outside.
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)
Upvotes: 2