如何在Python中旋转数组?

2024-03-29 09:12:59 发布

您现在位置: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)

Tags: 函数代码returndef错误数组array帖子
1条回答
网友
1楼 · 发布于 2024-03-29 09:12:59

您需要使用np.concatenate((A[K:],A[:K])) 如果是数组, 当Alist时,函数工作

以免试图从你的例子来看

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

相关问题 更多 >