代码1:
import numpy as np
np.random.seed(10)
p = np.random.randn(10, 10)
q = (p > 0)
i = 0
for qi in q.flat: # 使用q.flat来迭代所有元素
if qi:
i += 1
print(f"有{i}个元素大于零")
用flat将二维ndarray转化成一维用于迭代,用循环来查找,时间复杂度度O(n)
代码2:
import numpy as np
p = np.random.randn(10, 10)
q = (p > 0)
count_greater_than_zero = np.sum(q)
print(f"有{count_greater_than_zero}个元素大于零")
用sum对布尔值求和,Ture 为 1,False 为0, 时间复杂度度O(n)