确定多维numpy数组中是否至少有一个零 [英] Determine if there is at least one zero in a multidimensional numpy array

查看:172
本文介绍了确定多维numpy数组中是否至少有一个零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码: 存在一个numpy数组multidimensional_array,该数组要么具有所有整数且不包含零,要么具有多个整数中的零:

I have the following code: There exists a numpy array multidimensional_array which has either has all integers and no zeros, or one zero among many integers:

zeros_list = []   

for line in multidimensional_array:   # if find any zeros, append to list 'zeros'
    for x in line:
        if x.any() == 0:
            zeros_list.append(x)
        else:
            pass

for item in zeros:
    if item == 0:
        sys.stdout.write( 'True')   # if there is a zero, True
    else:
        sys.stdout.write( 'False')  # otherwise, False

不幸的是,这无法正常运行.如果为零,则输出True.如果没有,则什么也不会发生.每次我在python脚本script.py中运行此脚本时,都应该重置.我如何将其设置为"False"?

Unfortunately, this doesn't run correctly. If there's a zero, it outputs True. If not, nothing happens. Each time I run this within a python script script.py, it should reset. How can I set this to run 'False'?

推荐答案

对不起.它是一个[多维] numpy数组. numpy数组中是否存在一个零?那是测试

I am sorry. It is a [multidimensional] numpy array. Is there or is there not one zero in a numpy array? That's the test

好的,那会让我们到某个地方.您可以简单地发出

Alright, that will get us someplace. You can simply issue

0 in multidimensional_array

演示:

>>> import numpy as np
>>> test1 = np.arange(6).reshape(2,3)
>>> test1
array([[0, 1, 2],
       [3, 4, 5]])
>>> 0 in test1
True
>>> test1[0][0] = 42
>>> test1
array([[42,  1,  2],
   [ 3,  4,  5]])
>>> 0 in test1
False

这篇关于确定多维numpy数组中是否至少有一个零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆