繁体   English   中英

如何在 Python 中旋转数组?

[英]How to rotate an array in 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)

你需要使用np.concatenate((A[K:],A[:K]))如果 A 是一个数组,你的功能在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM