Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the result of 'counter'

Tags:

python

count

I count the occurrences of items in a list using

timesCrime = Counter(districts) 

Which gives me this:

Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868})

I want to separate the parts of the list items (3 and 1575 for example) and store them in a list of lists. How do I do this?

like image 633
Eowyn12 Avatar asked Apr 25 '16 20:04

Eowyn12


2 Answers

Counter is a dict, so you have the usual dict methods available:

>>> from collections import Counter
>>> counter = Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868})
>>> counter.items()
[(1, 868), (2, 1462), (3, 1575), (4, 1161), (5, 1159), (6, 1359)]

If you wanted them stored column major, just use some zip magic:

>>> zip(*counter.items())
[(1, 2, 3, 4, 5, 6), (868, 1462, 1575, 1161, 1159, 1359)]
like image 152
wim Avatar answered Sep 20 '22 15:09

wim


In [1]: from collections import Counter
In [2]: cnt = Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868})
In [3]: [cnt.keys(), cnt.values()]
Out[3]: [[1, 2, 3, 4, 5, 6], [868, 1462, 1575, 1161, 1159, 1359]]

A benchmark:

In [4]: %timeit zip(*cnt.items())
The slowest run took 5.62 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.06 µs per loop

In [5]: %timeit [cnt.keys(), cnt.values()]
The slowest run took 6.85 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 591 ns per loop

In case you want the output of Counter.items transformed into a list of lists:

In [5]: [list(item) for item in cnt.iteritems()]
Out[5]: [[1, 868], [2, 1462], [3, 1575], [4, 1161], [5, 1159], [6, 1359]]
like image 26
Eli Korvigo Avatar answered Sep 20 '22 15:09

Eli Korvigo