[英]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 是一個數組,你的功能在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.