Python程序将列表右旋转n
给定用户输入列表并给定轮换编号。我们的任务是从给定的轮换编号轮换列表。
示例
Input A= [2, 4, 5, 12, 90] rotation number=3 Output [ 90,12,2, 4, 5]
方法1
在这里,我们遍历列表中的每个元素,并将该元素插入第二个列表中所需的位置。
示例
def right_rotation(my_list, num): output_list = [] for item in range(len(my_list) - num, len(my_list)): output_list.append(my_list[item]) for item in range(0, len(my_list) - num): output_list.append(my_list[item]) return output_list # Driver Code A=list() n=int(input("Enter the size of the List")) print("Enter the number") for i in range(int(n)): p=int(input("n=")) A.append(int(p)) print (A) rot_num=int(input("Enter rotate number")) print("After rotation",right_rotation(A, rot_num)) python54.py
输出结果
Enter the size of the List 6 Enter the number n= 11 [11] n= 22 [11, 22] n= 33 [11, 22, 33] n= 44 [11, 22, 33, 44] n= 55 [11, 22, 33, 44, 55] n= 66 [11, 22, 33, 44, 55, 66] Enter rotate number 3 After rotation [44, 55, 66, 11, 22, 33]
方法2
在这里,我们使用切片技术len()
。
A=list() ni=int(input("Enter the size of the List")) print("Enter the number") for i in range(int(ni)): p=int(input("ni=")) A.append(int(p)) print (A) n = 3 A = (A[len(A) - n:len(A)] + A[0:len(A) - n]) print("After Rotation",A)
输出结果
Enter the size of the List 6 Enter the number ni= 11 [11] ni= 22 [11, 22] ni= 33 [11, 22, 33] ni= 44 [11, 22, 33, 44] ni= 55 [11, 22, 33, 44, 55] ni= 66 [11, 22, 33, 44, 55, 66] After Rotation [44, 55, 66, 11, 22, 33]
方法3
在此方法中,先获取列表A的最后n个元素,然后再获取列表A的其余元素。
示例
A=list() ni=int(input("Enter the size of the List")) print("Enter the number") for i in range(int(ni)): p=int(input("ni=")) A.append(int(p)) print (A) n = 3 A = (A[-n:] + A[:-n]) print("After Rotation",A)
输出结果
Enter the size of the List 6 Enter the number ni= 11 [11] ni= 22 [11, 22] ni= 33 [11, 22, 33] ni= 44 [11, 22, 33, 44] ni= 55 [11, 22, 33, 44, 55] ni= 66 [11, 22, 33, 44, 55, 66] After Rotation [44, 55, 66, 11, 22, 33]