Numpy 按位异或操作

NumPyNumPyBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习 Numpy 的 bitwise_xor() 函数,该函数主要用于执行按位异或(XOR)操作。我们将介绍其语法、参数以及多个代码示例,以帮助你更好地理解该函数。

虚拟机提示

虚拟机启动完成后,点击左上角切换到 Notebook 选项卡以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟,直到 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果在学习过程中遇到问题,请随时向 Labby 寻求帮助。实验结束后请提供反馈,我们将及时为你解决问题。

导入 Numpy 库

在开始使用 bitwise_xor() 函数之前,我们需要先导入 Numpy 库。可以通过以下代码实现:

import numpy as np

理解 bitwise_xor() 函数

bitwise_xor() 函数逐元素返回两个数组的按位异或(XOR)结果。它计算输入数组中整数的底层二进制表示的按位异或。该函数实现了 ^(C/Python 运算符)的 XOR 操作。

numpy.bitwise_xor(x1, x2, /, out, *, where=True, casting='same_kind', order='K', dtype, subok=True[, signature, extobj]) = <ufunc 'bitwise_xor'>

参数:

  • x1, x2:这两个是输入数组,该函数仅处理整数和布尔类型。
  • out:指示存储结果的位置。如果未提供,则返回一个新分配的数组。
  • where:一个广播到输入的条件。在条件为 True 的位置,输出数组将设置为 ufunc 的结果,否则输出数组将保留其原始值。

返回值:

如果 x1x2 都是标量,则该函数将返回一个标量。

bitwise_xor() 函数的使用示例

示例 1:

在这个示例中,我们将展示如何在两个标量值上使用 bitwise_xor() 函数。

num1 = 15
num2 = 20

print("The Input number1 is:", num1)
print("The Input number2 is:", num2)

output = np.bitwise_xor(num1, num2)
print("The bitwise_xor of 15 and 20 is:", output)

输出:

The Input number1 is: 15
The Input number2 is: 20
The bitwise_xor of 15 and 20 is: 27

示例 2:

在这个示例中,我们将使用两个数组,然后对它们应用 bitwise_xor() 函数。

ar1 = [2, 8, 135]
ar2 = [3, 5, 115]

print("The Input array1 is:", ar1)
print("The Input array2 is:", ar2)

output_arr = np.bitwise_xor(ar1, ar2)
print("The Output array after bitwise_xor:", output_arr)

输出:

The Input array1 is: [2, 8, 135]
The Input array2 is: [3, 5, 115]
The Output array after bitwise_xor: [  1  13 244]

总结

在本实验中,我们介绍了 Numpy 的 bitwise_xor() 函数。我们讨论了它的基本语法和参数,以及该函数返回的值,并提供了多个代码示例。