在 Numpy 中逐元素计算两个布尔数组的按位异或
numpyserver side programmingprogramming更新于 2025/9/19 7:56:00
要逐元素计算两个布尔数组的按位异或,请使用 Python Numpy 中的 numpy.bitwise_xor() 方法。
计算输入数组中整数的底层二进制表示的按位异或。此 ufunc 实现了 C/Python 运算符 ^。
第 1 个和第 2 个参数是数组,仅处理整数和布尔类型。如果 x1.shape != x2.shape,则它们必须可广播为通用形状。
步骤
首先,导入所需的库−
将 numpy 导入为 np
使用 array() 方法创建两个 numpy 布尔数组 −
arr1 = np.array([[False, False, False], [True, False, True]]) arr2 = np.array([[False, True, False], [False, False, False]])
显示数组 −
print("数组 1...
", arr1)
print("
数组 2...
", arr2)
获取数组的类型 −
print("
我们的数组 1 类型...
", arr1.dtype)
print("
我们的数组 2 类型...
", arr2.dtype)
获取数组的维度 −
print("
我们的数组 1 维度...
",arr1.ndim)
print("
我们的数组 2 维度...
",arr2.ndim)
获取数组的形状 −
print("
我们的数组 1 形状...
",arr1.shape)
print("
我们的数组 2 形状...
",arr2.shape)
要按元素计算两个布尔数组的按位异或,请使用 numpy.bitwise_xor() −
print("
结果(按位异或)...
",np.bitwise_xor(arr1, arr2))
示例
import numpy as np
# 使用 array() 方法创建两个 numpy 布尔数组
arr1 = np.array([[False, False, False],
[True, False, True]])
arr2 = np.array([[False, True, False],
[False, False, False]])
# 显示数组
print("数组 1...
", arr1)
print("
数组 2...
", arr2)
# 获取数组的类型
print("
我们的数组 1 类型...
", arr1.dtype)
print("
我们的数组 2 类型...
", arr2.dtype)
# 获取数组的维度
print("
我们的数组 1 维度...
",arr1.ndim)
print("
我们的数组 2 维度...
",arr2.ndim)
# 获取数组的形状
print("
我们的数组 1 形状...
",arr1.shape)
print("
我们的数组 2 形状...
",arr2.shape)
# 要按元素计算两个数组的按位异或,请使用 Python Numpy 中的 numpy.bitwise_xor() 方法
print("
结果(按位异或)...
",np.bitwise_xor(arr1, arr2))
输出
数组 1... [[False False False] [ True False True]] 数组 2... [[False True False] [False False False]] 我们的数组 1 类型... bool 我们的数组 2 类型... bool 我们的数组 1 维度... 2 我们的数组 2 维度... 2 我们的数组 1 形状... (2, 3) 我们的数组 2 形状... (2, 3) 结果(按位异或)... [[False True False] [ True False True]]

