[英]How to rotate an array in Python?
I'm trying to rotate an array in Python.我正在尝试在 Python 中旋转数组。 I've read the following post Python Array Rotation
我已经阅读了以下帖子Python Array Rotation
Where I found this little snippet of code我在哪里找到了这个小代码片段
arr = arr[numOfRotations:]+arr[:numOfRotations]
I've tried to put this into the following function:我试图将其放入以下函数中:
def solution(A, K):
A = A[K:] + A[:K]
print(A)
return A
Where A is my array and K is the number of rotations.其中 A 是我的数组,K 是旋转次数。 Only I get the following error, ValueError: operands could not be broadcast together with shapes (3,) (2,).
只有我收到以下错误,ValueError: 操作数无法与形状 (3,) (2,) 一起广播。
I don't understand where I'm going wrong?我不明白我哪里错了? Ideally I a solution that can solve this without using any Numpy inbuilt short cuts functions.
理想情况下,我是一个无需使用任何 Numpy 内置快捷功能即可解决此问题的解决方案。
Cheers干杯
Edit: This is the full program编辑:这是完整的程序
A = np.array([1, 2, 3, 4, 5])
def solution(A, K):
A = A[K:]+A[:K]
print(A)
return A
solution(A, 2)
You need to use np.concatenate((A[K:],A[:K]))
if A is an array, you function works when A
is list
你需要使用
np.concatenate((A[K:],A[:K]))
如果 A 是一个数组,你的功能在A
是list
Lest try to look at from your example以免尝试从您的示例中查看
A = np.array([1, 2, 3, 4, 5])
K = 2
print(A[K:])
print(A[:K])
Will give you [3 4 5]
and [1 2]
.会给你
[3 4 5]
和[1 2]
。 in your code you are trying to add them using +
sign.在您的代码中,您尝试使用
+
号添加它们。 Since the these two values are of different shapes you cant add them, hence you will get ValueError: operands could not be broadcast together with shapes (3,) (2,)
由于这两个值的形状不同,您无法将它们相加,因此您将收到
ValueError: operands could not be broadcast together with shapes (3,) (2,)
The correct implementation for an array will be数组的正确实现将是
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.