Python 程序将列表向右旋转 n 圈

programmingpythonserver side programming更新于 2025/3/14 17:48:17

在本文中,我们将了解如何从给定的旋转数向右旋转列表。列表在方括号之间有逗号分隔的值(项目)。关于列表的重要一点是列表中的项目不必是同一类型

假设以下是我们的输入列表 -

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]

相关文章


有用资源