Beginner
Beginner

Reputation: 147

Finding the occurrences in list

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'}]},
     {},
     {}]

Is there a way to print the count based on the max of each list?

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

Answers (3)

U13-Forward
U13-Forward

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

Sven-Eric Krüger
Sven-Eric Krüger

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

learner
learner

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

Related Questions