Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算列表中数组的特定元素的出现次数?_Python_Arrays_Python 2.7_Numpy - Fatal编程技术网

Python 如何计算列表中数组的特定元素的出现次数?

Python 如何计算列表中数组的特定元素的出现次数?,python,arrays,python-2.7,numpy,Python,Arrays,Python 2.7,Numpy,在一个数组很少的列表中,如何计算某个整数的出现次数?例如,我想查找值2的出现情况 import numpy as np a = [np.array([2, 2, 1, 2]), np.array([1, 3])] 预期输出: [3, 0] 有人能帮我吗?一种方法是使用计数器 In [3]: from collections import Counter 给出所有数字的频率 In [4]: [Counter(x) for x in a] Out[4]: [Counter({2: 3, 1:

在一个数组很少的列表中,如何计算某个整数的出现次数?例如,我想查找值2的出现情况

import numpy as np
a = [np.array([2, 2, 1, 2]), np.array([1, 3])]
预期输出:

[3, 0]

有人能帮我吗?

一种方法是使用
计数器

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]
In [7]: [np.bincount(x)[2] for x in a]
Out[7]: [3, 0]
或者,您可以使用
np.bincount
方法来计算非负整数数组中每个值的出现次数

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 [5]: [Counter(x)[2] for x in a]
Out[5]: [3, 0]
In [7]: [np.bincount(x)[2] for x in a]
Out[7]: [3, 0]

柜台是一个很好的选择。但是,由于您只需要检查嵌套列表中的某个值,也许简单的列表理解也可以:

>>> [sum(b==2) for b in a]
[3, 0]

使用
[a中b的sum(b==2)]
?x=[[array([-2,0,0])、array([-2,-1,1])、[array([3,-1])、array([1,-2])]使它更加简单。应用于此变量x时,返回错误。谢谢你的回答很有帮助。