簡體   English   中英

如何以自定義方式對列表項進行計數和排序?

[英]How can I count and order in a custom way items of a list?

我有一個鍵盤鍵列表,看起來像這樣(但更長):

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

我想計算它們並以鍵盤上出現的方式對它們進行排序。 例如,對於該列表,我想獲得 [2,0,0,0,1,0,2,...等]。 我知道 collections.Counter,但它只給出被按下的鍵。

你可以這樣做:

In [37]: keyboard_order = list('qwertyuiopasdfghjklzxcvbnm')

In [38]: pressed_keys = ['u', 'u', 't', 'q', 'q']

In [39]: from collections import defaultdict

In [40]: output = defaultdict(int)

In [41]: for key in pressed_keys:
    ...:     output[keyboard_order.index(key)] += 1
    ...:

In [42]: output
Out[42]: defaultdict(int, {6: 2, 4: 1, 0: 2})

In [43]: sorted(output)
Out[43]: [0, 4, 6]

我正在做的是創建鍵盤排序列表。 然后你只需要創建一個鍵和值為 0 的默認字典並計算頻率。 或者使用 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]

我認為這可以滿足您的需求:

from collections import Counter
keyboard = 'qwertyuiopasdfghjklzxcvbnm'
pressed_keys = ['u', 'u', 't', 'q', 'q', 's', 'p', 'a', 'm', 'h', 'a', 'm', 's', 't', 'e', 'r']
key_counts = Counter(pressed_keys)
[key_counts[k] for k in keyboard]

# [2, 0, 1, 1, 2, 0, 2, 0, 0, 1, 2, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM