0

In Python 3.x, I have a list of lists:

[['a','b','c'], ['a', 'c'], ['c', 'd'] ]

I saw this answer, but it only applies to a single list. How would I do this for a list of lists? My desired output would be a sorted list (or a sortable list) of the frequency of a particular item in a list.

Something like:

{a: 2, b: 1, c: 3, d: 1 }
Jeff
  • 4,148
  • 12
  • 58
  • 105

6 Answers6

3

You could use itertools.chain(*l) as an input to the Counter.

>>> l= [['a','b','c'], ['a', 'c'], ['c', 'd'] ]
>>> Counter(itertools.chain(*l))
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
abc
  • 10,886
  • 2
  • 22
  • 46
2

This may be solved using Counter. Counter creates a dictionary of the counts of the elements in the lists.

L = [['a','b','c'], ['a', 'c'], ['c', 'd'] ]
>>> from collections import Counter
>>> d = Counter()
>>> for sub in L:
    d.update(sub)


>>> d
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
Chris Charley
  • 6,091
  • 2
  • 21
  • 25
1

You can use Counter from collections to do this very efficiently:


In [161]: from collections import Counter
     ...: 
     ...: count = Counter()
     ...: 
     ...: lists = [['a','b','c'], ['a', 'c'], ['c', 'd']]
     ...: 
     ...: for sublist in lists:
     ...:     count += Counter(sublist)
     ...: 
     ...: print(count)
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})

This is "one-line-able" using python's builtin sum:

In [163]: from collections import Counter
     ...: lists = [['a','b','c'], ['a', 'c'], ['c', 'd']]
     ...: 
     ...: count = sum(map(Counter, lists), start=Counter())
     ...: 
     ...: print(count)
Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
salt-die
  • 630
  • 3
  • 7
0

You can flatten the list and use Counter. If your list is arbitrarily nested.

from collections import Counter
def flatten(lst):
    if not isinstance(lst,list):
        return [lst]
    else:
        return [j for i in lst for j in flatten(i)]

print(Counter(flatten([['a','b','c'], ['a', 'c'], ['c', 'd'] ])))
#Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
Ch3steR
  • 19,076
  • 4
  • 25
  • 52
0

You can do by itering in each sublist:

dict={} 
for sublist in list:
    for item in sublist:
        if item in dict.keys():
            dict[item] +=1
        else:
            dict[item] =1
Renaud
  • 2,334
  • 2
  • 9
  • 23
0

you can flatten your list and apply collections.Counter:

from collections import Counter

l = [['a','b','c'], ['a', 'c'], ['c', 'd'] ]
Counter((e for i in l for e in i))
kederrac
  • 15,932
  • 5
  • 29
  • 52