在 Python 中移位或旋转数组

您所在的位置:网站首页 二维数组旋转算法怎么写 在 Python 中移位或旋转数组

在 Python 中移位或旋转数组

2024-07-11 04:15| 来源: 网络整理| 查看: 265

在 Python 中使用 collections 模块移位数组 在 Python 中使用 numpy.roll() 方法移位数组 在 Python 中使用数组切片移位数组

本文将解释如何在 Python 中向左或向右移位或旋转数组。旋转数组意味着我们将数组的每个值向左侧或右侧移位或移位 n 个位置。最右边或最左边的元素移位到数组的另一端。

我们可以使用下面解释的各种方法在 Python 中移位或旋转数组。

在 Python 中使用 collections 模块移位数组

我们可以使用 collections 模块的 deque.rotate(n) 方法在 Python 中旋转数组。deque.rotate(n) 方法旋转 deque 类对象 n 个位置,其中 n 的符号表示是向左还是向右旋转 deque。

如果 n 的值为正,则输入将从左向右旋转,如果 n 为负,则输入将从右向左旋转。下面的代码演示了如何在 Python 中使用 deque.rotate(n) 方法旋转数组。

from collections import deque myarray = deque([1, 2, 3, 4, 5, 6]) myarray.rotate(2) # rotate right print(list(myarray)) myarray.rotate(-3) # rotate left print(list(myarray))

输出:

[5, 6, 1, 2, 3, 4] [2, 3, 4, 5, 6, 1] 在 Python 中使用 numpy.roll() 方法移位数组

numpy.roll(array, shift, axis) 方法将 array 作为输入并将其旋转到等于 shift 值的位置。如果 array 是一个二维数组,我们需要指定我们需要在哪个轴上应用旋转;否则,numpy.roll() 方法将在两个轴上应用旋转。

就像 deque.rotate() 方法一样,numpy.roll() 也会在值为正时从右向左旋转数组,如果值为负数则从右向左旋转。下面的示例代码演示了如何使用 numpy.roll() 方法在 Python 中旋转数组。

import numpy as np myarray = np.array([1, 2, 3, 4, 5, 6]) newarray = np.roll(myarray, 2) # rotate right print(newarray) newarray = np.roll(myarray, -2) # rotate left print(newarray)

输出:

[5 6 1 2 3 4] [3 4 5 6 1 2] 在 Python 中使用数组切片移位数组

我们还可以使用 Python 中的数组切片来实现旋转功能。此方法不需要任何额外的库,但效率低于上述方法。

下面的示例代码演示了如何在 Python 中使用数组切片来旋转或移位数组。

def rotate(input, n): return input[n:] + input[:n] myarray = [1, 3, 5, 7, 9] print(rotate(myarray, 2)) # rotate left print(rotate(myarray, -2)) # rotate right

输出:

[5, 7, 9, 1, 3] [7, 9, 1, 3, 5]


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3