我需要找到一种方法来计算从 0 到 9 的每个数字在使用 np.random.randint()
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
例如,如果矩阵的长度 = 4
- [[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]
数字 4 出现了多少次?它应该返回 5。
最佳答案
你应该能够很简单地得到这个:
list(m.flatten()).count(x)
另一个可能更快的选择是使用 numpy 内置 count_nonzero()
:
np.count_nonzero(m == x)
内置函数万岁。
关于python - 一个数字在 numpy 数组中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067471/