Python 实现通过n进行列表的右旋转
在本文中,我们将看到如何通过给定的旋转次数对列表进行右旋转。列表在方括号之间包含逗号分隔的值(项)。列表的重要特点是列表中的项不一定是相同类型的。
假设以下是我们的输入列表−
myList = [5, 20, 34, 67, 89, 94, 98, 110]
以下是n = 4 的输出 −
89, 94, 98, 110, 5, 20, 34, 67
将一个列表向右旋转n个元素,使用切片操作实现
在这里,使用切片操作可以实现列表的向右旋转 −
示例
# Create a List
myList =[5, 20, 34, 67, 89, 94, 98, 110]
print("List before rotation = ",myList)
# The value of n for rotation position
n = 4
# Rotating the List
myList = (myList[len(myList) - n:len(myList)] + myList[0:len(myList) - n])
# Display the Update List after rotation
print("Updated List after rotation = ",myList)
输出
List before rotation = [5, 20, 34, 67, 89, 94, 98, 110]
Updated List after rotation = [89, 94, 98, 110, 5, 20, 34, 67]
通过 if 右旋转一个 n 的列表
这里,if 语句用于右旋转一个列表 –
示例
# Create a List
myList =[5, 20, 34, 67, 89, 94, 98, 110]
print("List before rotation = ",myList)
# The value of n for rotation position
n = 4
# Rotating the List
if n>len(myList):
n = int(n%len(myList))
myList = (myList[-n:] + myList[:-n])
# Display the Update List after rotation
print("Updated List after rotation = ",myList)
输出
List before rotation = [5, 20, 34, 67, 89, 94, 98, 110]
Updated List after rotation = [89, 94, 98, 110, 5, 20, 34, 67]
通过for循环将列表向右旋转n个元素
在这里,我们使用for循环来右旋列表 –
示例
# The value of n for rotation position
num = 4
# Create a List
myList =[5, 20, 34, 67, 89, 94, 98, 110]
print("List before rotation = ",myList)
newlist = []
for item in range(len(myList) - num, len(myList)): newlist.append(myList[item])
for item in range(0, len(myList) - num): newlist.append(myList[item])
# Display the Update List after rotation
print("Updated List after rotation = ",newlist)
输出
List before rotation = [5, 20, 34, 67, 89, 94, 98, 110]
Updated List after rotation = [89, 94, 98, 110, 5, 20, 34, 67]