介绍
left_shift() 函数是 NumPy 库中的一个二进制操作,它对整数的位执行左移操作。本教程将引导你了解 left_shift() 函数的基本语法、参数和返回值,并包含一些使用该函数的示例。
虚拟机提示
虚拟机启动完成后,点击左上角切换到 Notebook 标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟,直到 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时可以询问 Labby。在课程结束后提供反馈,我们将及时为你解决问题。
导入 NumPy 库
首先,我们必须导入 NumPy 库以使用 left_shift() 函数。
import numpy as np
对单个值使用 left_shift()
left_shift() 函数用于将单个整数值的位向左移动指定的位数。以下是一个示例:
input_num = 40
bit_shift = 2
output = np.left_shift(input_num, bit_shift)
print(f"After shifting {bit_shift} bits to the left, the value is: {output}")
输出:
After shifting 2 bits to the left, the value is: 160
对值数组使用 left_shift()
left_shift() 函数也可以用于整数值数组。在这种情况下,该函数将对数组中的每个元素执行左移操作。以下是一个示例:
input_arr = np.array([2, 8, 10])
bit_shift = np.array([3, 4, 5])
output = np.left_shift(input_arr, bit_shift)
print(f"After shifting the bits to the left, the array is:\n{output}")
输出:
After shifting the bits to the left, the array is:
[ 16 128 320]
left_shift() 函数对两个数组中的每个元素都应用了左移操作。
指定输出数组
你可以指定一个输出数组来存储左移操作的结果。如果你提供了一个输出数组,函数将更新该数组,而不是分配一个新的数组。输出数组必须能够广播(broadcastable)到与输入数组相同的形状。以下是一个示例:
input_arr = np.array([2, 8, 10])
bit_shift = np.array([3, 4, 5])
output = np.zeros_like(input_arr, dtype=np.int64)
np.left_shift(input_arr, bit_shift, out=output)
print(f"After shifting the bits to the left, the output array is:\n{output}")
输出:
After shifting the bits to the left, the output array is:
[ 16 128 320]
指定输出的条件
你还可以通过 where 参数指定一个条件来设置输出数组的值。where 参数是一个布尔数组,它可以广播(broadcastable)到输入数组。以下是一个示例:
input_arr = np.array([2, 8, 10])
bit_shift = np.array([3, 4, 5])
output = np.zeros_like(input_arr, dtype=np.int64)
condition = np.array([True, False, True])
np.left_shift(input_arr, bit_shift, out=output, where=condition)
print(f"After shifting the bits to the left, the output array is:\n{output}")
输出:
After shifting the bits to the left, the output array is:
[ 16 8 320]
where 参数根据我们指定的条件设置了输出数组的第一个和第三个元素。
总结
本教程概述了 NumPy 库中的 left_shift() 函数。我们解释了其基本语法和参数,并展示了该函数返回的值。我们还提供了代码示例,演示了如何在单个值和数组值上使用该函数,以及如何指定输出数组和输出条件。