-1

Is there a pythonic way to count the elements in a list of lists preferably using collections?

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

Out:

1: 2
2: 2
3: 1
4: 1
5: 1
6: 1
Noelkd
  • 7,686
  • 2
  • 29
  • 43
Abhishek Thakur
  • 16,337
  • 15
  • 66
  • 97
  • Anything you tried that you want to share with us? – Tim Jun 05 '14 at 12:14
  • 2
    *preferably using collections*. Presumably you already looked and found [`collections.Counter()`](https://docs.python.org/2/library/collections.html#collections.Counter) then? What problems did you encounter making that work? – Martijn Pieters Jun 05 '14 at 12:15
  • `sum(map(Counter, lol), Counter())`, short but slower compared to itertools version. – Ashwini Chaudhary Jun 05 '14 at 12:19
  • @sundarnatarajサンダーナタラジ Sure, but also point out that this is less efficient in comparison to itertools version. – Ashwini Chaudhary Jun 05 '14 at 12:23
  • @MartijnPieters I dont think this is a duplicate as the other question is asking for count of a single element at a time. Not all of them! – Abhishek Thakur Jun 05 '14 at 12:29
  • @AbhishekThakur: you'll need to address 200 OK about that one; I voted to close as 'unclear what you are asking' because your question lacked any detail as to where you were stuck. – Martijn Pieters Jun 05 '14 at 12:32
  • @AbhishekThakur Did you see Imran's [answer](http://stackoverflow.com/a/5828150/846892) there? None of the answers here add nothing new to it. – Ashwini Chaudhary Jun 05 '14 at 12:32
  • 2
    @200OK, I think there's a case to be made that this is not a duplicate _of that question_. That question has an answer to this question, but that doesn't necessarily make this a duplicate of that question. However I am certain that this has been asked before. – senderle Jun 05 '14 at 12:34
  • It's also almost a duplicate of [this question](http://stackoverflow.com/q/15151762/577088), and is an exact (imo) duplicate of [this question](http://stackoverflow.com/q/23098468/577088). – senderle Jun 05 '14 at 12:39

2 Answers2

3
from collections import Counter
import itertools
a= [[1,2,3],[4,2],[5,1,6]]

print Counter(itertools.chain(*a))

#output Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1})

b=Counter(itertools.chain(*a))
for key,val in b.iteritems():
    print key,':',val

output:

1 : 2
2 : 2
3 : 1
4 : 1
5 : 1
6 : 1

Other way of doing this but less efficient compared to itertools( thanks to 200OK)

a= [[1,2,3],[4,2],[5,1,6]]
sum(map(Counter, a), Counter())
#output {1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1}
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
0
from collections import Counter
import itertools
lol = [[1,2,3],[4,2],[5,1,6]]
Counter(itertools.chain.from_iterable(lol))

Output

Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1})
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218