首页 > 解决方案 > 如何以自定义方式对列表项进行计数和排序?

问题描述

我有一个键盘键列表,看起来像这样(但更长):

pressed_keys = ['u', 'u', 't', 'q', 'q']

我想计算它们并以键盘上出现的方式对它们进行排序。例如,对于该列表,我想获得 [2,0,0,0,1,0,2,...etc] 。我知道 collections.Counter,但它只给出被按下的键。

标签: pythonlistcount

解决方案


使用 numpy 很容易:

import numpy as np

pressed_keys = ['u', 'u', 't', 'q', 'q','q']
pk = np.array(pressed_keys)                        # create a numpy array
chars, counts = np.unique(pk, return_counts=True)  # get the unique elements and count them

print(chars)
print(counts)

这使

['q' 't' 'u']
[3 1 2]

现在,让我们介绍一个(任意)键盘并将计数插入到正确的位置:

keyboard = np.array(['a', 'b', 'u', 'f', 't', 'g', 'q', 'x', 'y', 'z'])  # an arbitrary keyboard
key_hits = np.zeros(len(keyboard),dtype=int)                             # initialize the key hits with zero
for ch, co in zip(chars, counts):                                        # insert the counts at the right place
    key_hits[np.isin(keyboard, ch)] = co

print(keyboard)
print(key_hits)

这使:

['a' 'b' 'u' 'f' 't' 'g' 'q' 'x' 'y' 'z']
[0 0 2 0 1 0 3 0 0 0]

推荐阅读