拆分'柜台'的结果

Eow*_*n12 7 python count

我使用计算列表中项目的出现次数

timesCrime = Counter(districts) 
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868})
Run Code Online (Sandbox Code Playgroud)

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

wim*_*wim 8

Counter是一个dict,所以你有通常的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)]
Run Code Online (Sandbox Code Playgroud)

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

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


Eli*_*igo 5

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]]
Run Code Online (Sandbox Code Playgroud)

一个基准:

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
Run Code Online (Sandbox Code Playgroud)

如果您希望将输出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]]
Run Code Online (Sandbox Code Playgroud)