2016-04-25 11 views
7

policzyć wystąpień elementów na liście, używającSplit wynik „licznik”

timesCrime = Counter(districts) 

co mnie daje to:

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

Chcę oddzielić części elementów listy (3 i 1575 na przykład) i zapisać je na liście list. Jak to zrobić?

+1

Jesteś w zasadzie pytaniem, jak stosowanie .keys i .values –

Odpowiedz

3
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 

W przypadku, gdy chcesz wyjście Counter.items przekształcona w liście list:

In [5]: [list(item) for item in cnt.iteritems()] 
Out[5]: [[1, 868], [2, 1462], [3, 1575], [4, 1161], [5, 1159], [6, 1359]] 
8

Counter jest dict, więc trzeba zwykle dict metod dostępnych:

>>> 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)] 

Jeśli chcesz je przechowywać kolumny dur, wystarczy użyć trochę zip Magic:

>>> zip(*counter.items()) 
[(1, 2, 3, 4, 5, 6), (868, 1462, 1575, 1161, 1159, 1359)]