19
['a','a','b','c','c','c']

to

[2, 2, 1, 3, 3, 3]

and

{'a': 2, 'c': 3, 'b': 1}
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
user288832
  • 899
  • 2
  • 7
  • 9

8 Answers8

40
>>> x=['a','a','b','c','c','c']
>>> map(x.count,x)
[2, 2, 1, 3, 3, 3]
>>> dict(zip(x,map(x.count,x)))
{'a': 2, 'c': 3, 'b': 1}
>>>
YOU
  • 114,140
  • 31
  • 183
  • 213
  • 4
    The result looks pretty, but it has potential O(n^2) runtime behaviour. – Juergen Mar 08 '10 at 14:38
  • 2
    But he never said anything about performance... this solves the problem, if it's too inefficient that's a different problem to solve. – chills42 Mar 08 '10 at 14:48
  • 3
    That is right -- but did you ever realize what can happen, wenn you run into the O(n^2)-trap? I experienced it, when a simple algorithm killed program performance totally because it happened to be a bigger dataset and the algorithm had such behaviour. – Juergen Mar 08 '10 at 15:29
  • 4
    Relax. You're most likely writing O(n^3) and O(2^n) algorithms all the time, and never even notice them being executed. Solve those problems **if** they happen. – Wim Mar 10 '10 at 20:54
12

This coding should give the result:

from collections import defaultdict

myDict = defaultdict(int)

for x in mylist:
  myDict[x] += 1

Of course if you want the list inbetween result, just get the values from the dict (mydict.values()).

Juergen
  • 11,840
  • 7
  • 36
  • 54
6

Use a set to only count each item once, use the list method count to count them, store them in a dict with the item as key and the occurrence is value.

l=["a","a","b","c","c","c"]
d={}

for i in set(l):
    d[i] = l.count(i)

print d

Output:

{'a': 2, 'c': 3, 'b': 1}
Mizipzor
  • 48,671
  • 21
  • 94
  • 137
  • for me this is the most simple to understand/implement. Do you know if its slower than using the collections Counter? – zach May 27 '12 at 19:14
  • For such trivial examples, implement them both and time them. Don't trust my guesses. Or rather, don't care about the speed at all; you're using Python for simplicity, not performance. – Mizipzor May 28 '12 at 14:59
6

On Python ≥2.7 or ≥3.1, we have a built-in data structure collections.Counter to tally a list

>>> l = ['a','a','b','c','c','c']
>>> Counter(l)
Counter({'c': 3, 'a': 2, 'b': 1})

It is easy to build [2, 2, 1, 3, 3, 3] afterwards.

>>> c = _
>>> [c[i] for i in l]   # or map(c.__getitem__, l)
[2, 2, 1, 3, 3, 3]
kennytm
  • 491,404
  • 99
  • 1,053
  • 989
5
a = ['a','a','b','c','c','c']
b = [a.count(x) for x in a]
c = dict(zip(a, b))

I've included Wim answer. Great idea

luc
  • 39,890
  • 22
  • 125
  • 171
3

Second one could be just

dict(zip(['a','a','b','c','c','c'], [2, 2, 1, 3, 3, 3]))
Wim
  • 10,833
  • 38
  • 56
2

For the first one:

l = ['a','a','b','c','c','c']

map(l.count,l)

JonT
  • 57
  • 4
1
d=defaultdict(int)
for i in list_to_be_counted: d[i]+=1
l = [d[i] for i in list_to_be_counted]
starhusker
  • 5,870
  • 3
  • 17
  • 12