python - 如何以自定义方式对列表项进行计数和排序?
问题描述
我有一个键盘键列表,看起来像这样(但更长):
pressed_keys = ['u', 'u', 't', 'q', 'q']
我想计算它们并以键盘上出现的方式对它们进行排序。例如,对于该列表,我想获得 [2,0,0,0,1,0,2,...etc] 。我知道 collections.Counter,但它只给出被按下的键。
解决方案
使用 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]
推荐阅读
- javascript - How to type useRef hook in Flow?
- c# - How to update the cookies in Httpclient instance which created via HttpClientFactory -C#
- curl - Autodesk Forge - 使用 cURL 和 cmd 提示符获取访问令牌
- python - 如何更新 MySQL 数据库中的 Django 模型字段
- node.js - 如何从我的 Lambda NodeJS 中的 serverless.yml 获取服务名称和函数名称?
- python - 导入 Python 模块 adafruit_pca9685 时出现问题
- reactjs - 将 react native android 转换为 react native web @react-native-picker/picker 错误
- android - Android中的com.google.android.material.button.MaterialButton“OutlinedButton”样式
- sql - 以复杂布尔表达式为列的 SQL 查询
- c# - 如何在 LIST 或 LAMBDA EXPRESSION 中使用 STATIC 类值?