我需要找到一种方法来计算在使用np.random.randint()
创建的随机矩阵中,数字0到9出现的次数。
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]]
我需要找到一种方法来计算在使用np.random.randint()
创建的随机矩阵中,数字0到9出现的次数。
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
list(m.flatten()).count(x)
另一个可能更快的选项是使用numpy内置的count_nonzero()
函数:
np.count_nonzero(m == x)
太棒了,内置函数。
sum
函数:In [52]: m = np.random.randint(0,9,(4,4))
In [53]: m
Out[53]:
array([[8, 8, 2, 1],
[2, 7, 1, 2],
[8, 6, 8, 7],
[5, 2, 5, 2]])
In [56]: np.sum(m == 8)
Out[56]: 4
m == 8
将返回一个布尔数组,其中包含每个值是否等于8的True值,由于Python将True视为1,您可以对数组项进行求和以获得预期项的数量。
(如果要查看文档,请点击以下链接:numpy.ndarray.flatten和collections.Counter)
import numpy as np
import collections
p = int(input("Length of matrix: "))
m = np.random.randint(0, 9, (p, p))
print(m)
print(collections.Counter(m.flatten()))
[[8 4 8]
[5 1 1]
[1 1 1]]
Counter({1: 5, 8: 2, 4: 1, 5: 1})
count()
方法:from collections import Counter
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
flat = [item for sublist in m for item in sublist]
flat.count(4)
flat.count(x)
就足够了。 - TemporalWolftimeit
进行测试。 - TemporalWolfflatten
),并将它们与rofls的自定义列表推导式解决方案进行比较。 - TemporalWolfimport numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
# print(m)
un, nm = np.unique(m, return_counts = True)
# if number that you are looking for is 1 then:
print(nm[un==1])