Home > Enterprise >  Python find frequency of numbers in list of lists
Python find frequency of numbers in list of lists

Time:08-09

I have a list of lists of int as shown below

[[1, 2, 3],
 [1, 5],
 [4, 2, 6]]

I want to generate the frequency of the numbers in the lists as a dict, for example 1 occurs in 2 of the lists, and so on, expected output is

{1:2,
 2:2,
 3:1,
 4:1,
 5:1,
 6:1}

How can this be generated?

CodePudding user response:

You could try this:

L is your list of list.
expected = {1:2, 2:2, 3:1, 4:1, 5:1, 6:1}


>>> from itertools import chain
>>> from collections import Counter
>>> flattened = list(chain.from_iterable(L))
>>> flattened
[1, 2, 3, 1, 5, 4, 2, 6]
>>> counts = Counter(flattened)
>>> counts
Counter({1: 2, 2: 2, 3: 1, 5: 1, 4: 1, 6: 1})

# It's easy to make it to a function or one-liner too.
>>> counts = Counter(chain.from_iterable(L))

>>> assert counts == expected     # your expected result shown above
#   silence means matching.

CodePudding user response:

you can use Counter for this

>>> from collections import Counter as c
>>> array = [[1, 2, 3],[1,5],[4,2,6]]
>>> result = c()
>>> for sublist in array:
...     result  = c(sublist)
... 
>>> result
Counter({1: 2, 2: 2, 3: 1, 5: 1, 4: 1, 6: 1})
  • Related