📜  Python|在列表中从前到后移动

📅  最后修改于: 2022-05-13 01:54:53.194000             🧑  作者: Mango

Python|在列表中从前到后移动

循环旋转已在前面的文章中讨论过。但有时,我们只需要一个特定的任务,即轮换的一部分,即将列表中的第一个元素移动到最后一个元素。这在某些实用程序的日常编程中有应用。让我们讨论一些可以实现这一目标的方法。

方法#1:使用列表切片和“+” operator
这些功能的组合可用于执行列表中的单次移位任务。第一个元素被添加到列表的其余部分以使用切片来完成此任务。

# Python3 code to demonstrate
# Shift from Front to Rear in List
# using list slicing and "+" operator
  
# initializing list 
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# using list slicing and "+" operator
# Shift from Front to Rear in List
test_list = test_list[1 :] + test_list[: 1] 
  
# printing result
print ("The list after shift is : " + str(test_list))
输出 :
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The list after shift is : [4, 5, 6, 7, 8, 9, 12, 1]

方法 #2:使用insert() + pop()
也可以使用Python viz 的内置函数来实现此功能。插入()和弹出()。 pop函数删除第一个元素,最后使用 insert函数插入。

# Python3 code to demonstrate
# Shift from Front to Rear in List
# using insert() + pop()
  
# initializing list 
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# using insert() + pop()
# Shift from Front to Rear in List
test_list.insert(len(test_list) - 1, test_list.pop(0))
  
# printing result
print ("The list after shift is : " + str(test_list))
输出 :
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The list after shift is : [4, 5, 6, 7, 8, 9, 12, 1]