一个数字在numpy数组中出现多少次

编程入门 行业动态 更新时间:2024-10-20 16:45:47
本文介绍了一个数字在numpy数组中出现多少次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要找到一种方法来计算从0到9的每个数字出现在使用 np.random.randint()

I need to find a way to count how many times each number from 0 to 9 appears in a random matrix created using np.random.randint()

import numpy as np p = int(input("Length of matrix: ")) m = np.random.randint(0,9,(p,p)) print(m)

例如,如果矩阵的长度= 4

For example if length of matrix = 4

  • [[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]

数字4出现几次?它应该返回5.

How many times does the number 4 appear? It should return 5.

推荐答案

您应该可以很简单地获得它:

You should be able to get this pretty simply:

list(m.flatten()).count(x)

另一个可能更快的选项是使用内置的numpy count_nonzero() :

Another option which is probably faster, is to use the numpy builtin count_nonzero():

np.count_nonzero(m == x)

Hooray内置函数.

Hooray builtin functions.

更多推荐

一个数字在numpy数组中出现多少次

本文发布于:2023-11-30 20:52:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多少次   组中   数字   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!