gpt4 book ai didi

python - 如何在 Python 中旋转数组?

转载 作者:行者123 更新时间:2023-12-04 12:57:43 27 4
gpt4 key购买 nike

我正在尝试在 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

关于python - 如何在 Python 中旋转数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64168142/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com