我试图每次使用 Python 将列表旋转两个

Im trying to rotate a list using Python by two each time

我写了一个代码,用户输入一个代码,程序将它旋转所需的量,但每次它旋转两个而不是一个。 例如。 1 2 3 4 5 旋转 1 会变成 4 5 1 2 3 我的代码是:

    arSize = int(input("Please enter the size of the list "))
    arr = []
    d = int(input("How many times do you want to rotate it to the right? :"))
    for i in range(0, arSize) :
     number = int(input("Please enter array[" + str(i) + "] value: "))
     arr.append(number)

    n = arSize

    def rightRotate(arr, d, n): 
      for i in range(d): 
        rightRotatebyTwo(arr, n) 

    def rightRotatebyTwo(arr, n):
      temp = arr[0]
      temp1 = arr[1]
      arr[1] = arr[n-1]
      arr[0] = arr[n-2]
      for i in range(2, n-1):
        temp2 = arr[i]
        temp3 = arr[i+1]
        arr[i] = temp
        arr[i+1] = temp1
        temp = temp1
        temp1 = temp2


    def printArray(arr, size): 
      for i in range(size): 
        print (arr[i]) 

    rightRotate(arr, d, n) 
    printArray(arr, n)

这是结果:

    Please enter the size of the list 6
    How many times do you want to rotate it to the right? :1
    Please enter array[0] value: 1
    Please enter array[1] value: 2
    Please enter array[2] value: 3
    Please enter array[3] value: 4
    Please enter array[4] value: 5
    Please enter array[5] value: 6
    5
    6
    1
    2
    3
    2

你的方法有点太绕了。您应该尝试不同的方法。

例如: 一个简单的切片操作就可以在这里工作。

def rotateRight(no_of_rotations):
    arr = [1, 2, 3, 4, 5] 
    arr = arr[no_of_rotations:] + arr[:no_of_rotations] 
    return arr 

祝一切顺利! :)