python - 如何在 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
推荐阅读
- ios - 在 UITableView 中默认启用重新排序控件而不处于编辑模式
- git - 如何获取添加为 git 子模块的依赖项的子依赖项
- html - 当第二个操作数具有“隐藏”属性时应用兄弟选择器
- spring-webflux - Spring webflux restdocs - 通过测试用例的安全性
- html - 如何在第一个对象之后和按钮对象之前正确附加?
- python - Python 和 MySQL 中的数据透视表
- javascript - 点击不打开文件对话框
- javascript - 为什么 App.cs 在每个组件中运行,而不是在其他 css 组件中运行?
- python-3.x - 无法从 sklearn.preprocessing 导入“MinMaxScaler”
- javascript - 从 React 中的对象生成链接列表以创建动态 API 路由