![](/img/trans.png)
[英]How do I count occurrences of a specific element in a position in a list of lists?
[英]How to count occurrences of specific element for arrays in a list?
如何計算具有少量數組的列表中某個整數的出現? 例如,我想查找值2的出現次數。
import numpy as np
a = [np.array([2, 2, 1, 2]), np.array([1, 3])]
預期產量:
[3, 0]
誰能幫我?
一種方法是使用Counter
In [3]: from collections import Counter
給出所有數字的頻率
In [4]: [Counter(x) for x in a]
Out[4]: [Counter({2: 3, 1: 1}), Counter({1: 1, 3: 1})]
只計算2
In [5]: [Counter(x)[2] for x in a]
Out[5]: [3, 0]
或者,您可以使用np.bincount
方法來計算非負的int數組中每個值的出現次數。
In [6]: [np.bincount(x) for x in a]
Out[6]: [array([0, 1, 3], dtype=int64), array([0, 1, 0, 1], dtype=int64)]
提取數字2
In [7]: [np.bincount(x)[2] for x in a]
Out[7]: [3, 0]
櫃台是一個很好的選擇。 但是,由於您只需要檢查嵌套列表中的某個值,也許簡單的列表理解也可以工作:
>>> [sum(b==2) for b in a]
[3, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.