简体   繁体   English

了解numpy的any函数

[英]Understanding numpy's any function

I came across a function named any with numpy and I could not understand its usage in some context which is given as folllows: 我遇到了一个用numpy命名为any的函数,在以下情况下我无法理解其用法:

if np.subtract(original.shape, duplicate.shape).any():
   # Do something
else:
   # Carry on with the usual tasks

Could someone help me understand what is happening here? 有人可以帮我了解这里发生了什么吗? What is being checked? 正在检查什么? The documentation says, 该文件说,

Tests whether any array element along a given axis evaluates to True. 测试沿给定轴的任何数组元素的求值是否为True。

Is it being checked for equality? 是否正在检查是否相等? To understand this better, how could I rewrite the any call? 为了更好地理解这一点,我该如何重写any电话?

It's being checked for "True"ness. 正在检查其“真实”性。

Try this: 尝试这个:

import numpy

print(numpy.any([0, 0, 0, 0, 0]))
print(numpy.any([0, 0, 0, 0, 1]))

np.any(x) checks if any of the elements in x is true. np.any(x)检查是否有任何在该元件的x是真实的。 In your case, it checks if the arrays original and duplicate have at least a different dimension. 在您的情况下,它将检查original数组和duplicate数组是否至少具有不同的维度。

You could rewrite this as: 您可以将其重写为:

res = False
for so, sd in zip(original.shape, duplicate.shape):
    if so != sd:
        res = True

if res:
    # Do something
else:
   # Carry on with the usual tasks

The any method checks if at least on element in the given data is evaluated as True . any方法检查至少给定数据中的on元素是否被评估为True

In python the following things are evaluated False : 在python中, 以下内容评估为False

  • None
  • False
  • any numeric zero 任何数字零
  • empty strings, sets, lists, dictionaries ... 空字符串,集合,列表,字典...
  • anything that has a __len__ method which returns 0 or a __bool__ method that returns False 具有__len__方法返回0或__bool__方法返回False任何东西

Everything else is evaluated True . 其他所有内容都评估为True

If the data checked by the any method contains at least one item that does not meet these requirements, it returns True else False 如果通过any方法检查的数据包含至少一个不满足这些要求的项目,则返回True否则为False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM