python中数组旋转的给定数量的移动

时间:2019-06-21 18:23:46

标签: python python-3.x

给出了一个长度为n且旋转了k的数组来执行。我已经尝试过,但是却出错了

shifted = []
size , rotation = [int(size)for size in input().split()]
arr= [int(size) for size in input().split()]
for loop in range(len(arr)):
  indx = (loop+rotation)%len(arr)
  shifted[indx:indx] = arr[loop]

print(shifted)

我收到此错误:     shifted [indx:indx] = arr [loop]     TypeError:只能分配一个可迭代的

1 个答案:

答案 0 :(得分:0)

假设向左旋转并输入:

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
n = 10

如果不需要就地执行此操作,则可以执行以下操作:

result = lst[k:] + lst[:k] # [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]

deque也是一个选择:

from collections import deque
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result = deque(lst)
result.rotate(-3) # Rotate 3 to the left
print(list(result))