How can I count for the occurrence of certain integer in a list with few arrays? For example I would like to look for the occurrences of the value 2.
如何计算具有少量数组的列表中某个整数的出现?例如,我想查找值2的出现次数。
import numpy as np
a = [np.array([2, 2, 1, 2]), np.array([1, 3])]
Expected output:
预期产量:
[3, 0]
Can anyone help me?
谁能帮我?
2 个解决方案
#1
5
One way is to use Counter
一种方法是使用Counter
In [3]: from collections import Counter
Gives frequencies of all numbers
给出所有数字的频率
In [4]: [Counter(x) for x in a]
Out[4]: [Counter({2: 3, 1: 1}), Counter({1: 1, 3: 1})]
To get count for only 2
只计算2
In [5]: [Counter(x)[2] for x in a]
Out[5]: [3, 0]
Alternatively, you could use np.bincount
method, to count number of occurrences of each value in array of non-negative ints.
或者,您可以使用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)]
Extract counts for number 2
提取数字2
In [7]: [np.bincount(x)[2] for x in a]
Out[7]: [3, 0]
#2
2
Counter is an excellent alternative. However, since you just need to check for a certain value within a nested list, perhaps a simple list comprehension would also work:
柜台是一个很好的选择。但是,由于您只需要在嵌套列表中检查某个值,也许简单的列表推导也可以起作用:
>>> [sum(b==2) for b in a]
[3, 0]
#1
5
One way is to use Counter
一种方法是使用Counter
In [3]: from collections import Counter
Gives frequencies of all numbers
给出所有数字的频率
In [4]: [Counter(x) for x in a]
Out[4]: [Counter({2: 3, 1: 1}), Counter({1: 1, 3: 1})]
To get count for only 2
只计算2
In [5]: [Counter(x)[2] for x in a]
Out[5]: [3, 0]
Alternatively, you could use np.bincount
method, to count number of occurrences of each value in array of non-negative ints.
或者,您可以使用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)]
Extract counts for number 2
提取数字2
In [7]: [np.bincount(x)[2] for x in a]
Out[7]: [3, 0]
#2
2
Counter is an excellent alternative. However, since you just need to check for a certain value within a nested list, perhaps a simple list comprehension would also work:
柜台是一个很好的选择。但是,由于您只需要在嵌套列表中检查某个值,也许简单的列表推导也可以起作用:
>>> [sum(b==2) for b in a]
[3, 0]