不运算符,在Python中看起来错误?

2024-04-27 03:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,创建了一个小函数来进行聚类分析。 最简单的是我必须多次比较两个数组,直到它不再改变。为此我使用了while循环,只要它们不相等,我就会得到两个不同的结果!=而不是==。中全景:

import numpy as np

a = np.array([1,1,1])
b = np.array([1,2,1])

print((a != b).all())
print(not (a == b))

Tags: 函数importnumpyasnpnot数组all
3条回答

以下两个表达式相等。当至少有一个不同的元素时,它们返回true。你知道吗

print((a != b).any())
print(not (a == b).all())

下面两个也给出了相同的结果。当两个数组中相同位置的每个元素都不同时,它们返回true。你知道吗

print((a != b).all())
print(not (a == b).any())

not (a == b)将引发ValueError,因为包含多个元素的数组的真值不明确。你知道吗

在numpy中反转布尔数组的方法是使用~运算符:

>>> a != b
array([False,  True, False], dtype=bool)
>>> ~ (a == b)
array([False,  True, False], dtype=bool)
>>> (~ (a == b)).all() == (a != b).all()
True

要了解更多信息,请看下面的代码,您希望比较dc,但这两个都是数组,因此您应该正确比较,而不是通过not运算符!!你知道吗

a = np.array([1,1,1])
b = np.array([1,2,1])
c = (a!=b)
type(c)
Out[6]: numpy.ndarray
type(a)
Out[7]: numpy.ndarray
c
Out[8]: array([False,  True, False], dtype=bool)
c.all()
Out[9]: False
d = (a==b)
type(d)
Out[11]: numpy.ndarray
d
Out[12]: array([ True, False,  True], dtype=bool)
not d
                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-13-84cd3b926fb6> in <module>()
  > 1 not d

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

not(d.any())
Out[15]: False

x = d.any()
type(x)
Out[19]: numpy.bool_

相关问题 更多 >