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?
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)]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With