Reputation: 103
This most likely has been asked before but I can't seem to find a straight forward solution. Say I have a bunch of numbers in a list like:
1234
2233
3232
1234
I need to find a way to print the frequency total for the items in the list using a script, so something like this:
1234 2
2233 1
3232 1
Can someone shed some light on this for me?
Thank you
Upvotes: 0
Views: 118
Reputation: 50540
from collections import Counter
l = [1234,2233,3232,1234]
c = Counter(l)
print c
Outputs:
Counter({1234: 2, 3232: 1, 2233: 1})
Explanation:
This utilizes the collections.Counter
. It returns a dict
like object (technically, Counter
is a subclass of dict
). This means that you can do something like:
print c[1234]
and get a result of
2
Another option you have, if you aren't looking for a dictionary like object, is to build a list of tuples that contains the value/count pairs.
zip(Counter(l).keys(), Counter(l).values())
This returns something like this:
[(3232, 1), (2233, 1), (1234, 2)]
The Counter class was added in Python 2.7. Based on the error you posted to another answer, it seems you are using 2.6 or older. You can either upgrade to 2.7, or you can utilize the backport of the Counter class.
You could also use defaultdict
and count the items:
from collections import defaultdict
l = [1234,2233,3232,1234]
d = defaultdict(int)
for curr in l:
d[curr] += 1
print d
d
is a dictionary that looks like this:
defaultdict(<type 'int'>, {3232: 1, 2233: 1, 1234: 2})
You can access this the same way you would with the Counter
:
d[1234]
prints
2
Upvotes: 5
Reputation: 1273
The code below
from itertools import groupby
a = [
1234,
2233,
3232,
1234
]
print [(key, len(list(group))) for key, group in groupby(sorted(a))]
Will give you:
[(1234, 2), (2233, 1), (3232, 1)]
Upvotes: 1
Reputation: 86138
You can use collections.Counter
In [1]: from collections import Counter
In [2]: my_list = [1,3,3,2]
In [3]: Counter(my_list)
Out[3]: Counter({3: 2, 1: 1, 2: 1})
Upvotes: 3