Home > Back-end >  Count the frenquency of an item which appears in the sublist of a list-Python
Count the frenquency of an item which appears in the sublist of a list-Python

Time:11-16

I am writing Python, and I want to count the times of an item appears in a list(which is made up by multiple sublist)

a = [[3,2,5,6],[2,5,1,20],[7,3,16,5]]

The result: 3->2 times ; 1->1 time; 5->3 times

Heres the things, I do not want to use loop.!!

Is there any other way? Thank you for helping. :)

CodePudding user response:

It is not possible to do this without doing any loops. Comprehensions are loops. Counter uses a loop internally. Here is one possible answer:

from collections import Counter
Counter(e for s in a for e in s)
# => Counter({5: 3, 3: 2, 2: 2, 6: 1, 1: 1, 20: 1, 7: 1, 16: 1})

CodePudding user response:

You could do it using High order functions. Specifically filters:

a = [[3,2,5,6],[2,5,1,20],[7,3,16,5]]

# n: The number you want to search
n = 3

count = len(list(filter(lambda x: n in x, a)))

print(count)
  • Related