如何在 Python 中旋转数组?
How to rotate an array in Python?
我正在尝试旋转 Python 中的数组。我已阅读以下内容 post Python Array Rotation
我在哪里找到这段代码
arr = arr[numOfRotations:]+arr[:numOfRotations]
我尝试将其放入以下函数中:
def solution(A, K):
A = A[K:] + A[:K]
print(A)
return A
其中A是我的数组,K是旋转数。只有我得到以下错误,ValueError: operands could not be broadcast together with shapes (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 是一个数组,
当 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
我正在尝试旋转 Python 中的数组。我已阅读以下内容 post Python Array Rotation
我在哪里找到这段代码
arr = arr[numOfRotations:]+arr[:numOfRotations]
我尝试将其放入以下函数中:
def solution(A, K):
A = A[K:] + A[:K]
print(A)
return A
其中A是我的数组,K是旋转数。只有我得到以下错误,ValueError: operands could not be broadcast together with shapes (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 是一个数组,
当 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