📜  Python|在列表中移动子列表

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

Python|在列表中移动子列表

有时,在使用列表时,我们可能会遇到需要将某些子列表移动到同一子列表中的所需索引的问题。在白天编程中可能会出现此问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用insert() + pop() + 循环
上述功能的组合可用于执行特定任务。 pop函数可用于删除子列表, insert函数可用于插入子列表。这发生在循环中的单次迭代中的每个元素。

# Python3 code to demonstrate working of
# Shift sublist in list
# Using insert() + pop() + loop
  
# function to perform the task 
def shift_sublist(test_list, strt_idx, no_ele, shft_idx):
    for ele in range(no_ele):
        test_list.insert(shft_idx + 1, test_list.pop(strt_idx))
    return test_list
  
# initializing list
test_list = [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
  
# printing original list
print("The original list is : " +  str(test_list))
  
# Using insert() + pop() + loop
# Shift sublist in list
res = shift_sublist(test_list, 2, 3, 6)
  
# Printing result
print("The list after shift of sublist : " +  str(res))
输出 :

方法#2:使用列表切片
此任务也可以使用列表切片技术,其中只需在所需位置添加列表的不同部分。

# Python3 code to demonstrate working of
# Shift sublist in list
# Using list slicing
  
# function to perform the task 
def shift_sublist(test_list, strt_idx, no_ele, shft_idx):
    return (test_list[:strt_idx] + test_list[strt_idx + no_ele : no_ele + shft_idx - 1]
            + test_list[strt_idx : strt_idx + no_ele] + test_list[shft_idx + no_ele -1:])
  
# initializing list
test_list = [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
  
# printing original list
print("The original list is : " +  str(test_list))
  
# Using list slicing
# Shift sublist in list
res = shift_sublist(test_list, 2, 3, 6)
  
# Printing result
print("The list after shift of sublist : " +  str(res))
输出 :
The original list is : [4, 5, 6, 7, 3, 8, 10, 1, 12, 15, 16]
The list after shift of sublist : [4, 5, 8, 10, 1, 6, 7, 3, 12, 15, 16]