拆分' counter'的结果

时间:2016-04-25 20:34:18

标签: python count

我使用

计算列表中项目的出现次数
timesCrime = Counter(districts) 

这给了我这个:

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

我想分隔列表项的部分(例如3和1575)并将它们存储在列表列表中。 我该怎么做?

2 个答案:

答案 0 :(得分:8)

Counterdict,因此您可以使用通常的dict方法:

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

如果你想让它们存储专栏,只需使用一些zip魔法:

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

答案 1 :(得分:4)

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

基准:

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

如果您希望将Counter.items的输出转换为列表列表:

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