首页 > 解决方案 > 如何在 Python 中旋转数组?

问题描述

我正在尝试在 Python 中旋转一个数组。我已阅读以下文章Python Array Rotation

我在哪里找到这个小代码片段

arr = arr[numOfRotations:]+arr[:numOfRotations]

我试图将其放入以下函数中:

def solution(A, K):
    A = A[K:] + A[:K]
    print(A)
    return A

其中 A 是我的数组,K 是旋转次数。只有我得到以下错误,ValueError:操作数无法与形状(3,)(2,)一起广播。

我不明白我哪里出错了?理想情况下,我可以在不使用任何 Numpy 内置快捷方式功能的情况下解决此问题。

干杯

编辑:这是完整的程序

A = np.array([1, 2, 3, 4, 5])

def solution(A, K):
    A = A[K:]+A[:K]
    print(A)
    return A

solution(A, 2)

标签: pythonarraysnumpyrotation

解决方案


np.concatenate((A[K:],A[:K])) 如果 A 是数组,则需要使用,函数A何时起作用list

以免尝试从您的示例中查看

A = np.array([1, 2, 3, 4, 5])
K = 2
print(A[K:])
print(A[:K])

会给你[3 4 5][1 2]。在您的代码中,您尝试使用+符号添加它们。由于这两个值的形状不同,您无法添加它们,因此您将得到ValueError: operands could not be broadcast together with shapes (3,) (2,)

数组的正确实现将是

import numpy as np
A = np.array([1, 2, 3, 4, 5])

def solution(A, K):
    A = np.concatenate((A[K:],A[:K]))
    print(A)
    return A

推荐阅读