📜  Python - 从初始元素替换子列表

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

Python - 从初始元素替换子列表

给定一个列表和替换子列表,根据替换子列表的初始元素执行列表子列表的替换。

方法:使用列表理解+列表切片
上述功能的组合可以用来解决这个问题。在此,我们提取开始元素的索引,然后根据需要对列表进行适当的切片。

# Python3 code to demonstrate working of 
# Replace substring from Initial element
# Using list slicing + list comprehension
  
# initializing list
test_list = [5, 2, 6, 4, 7, 1, 3]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing repl_list 
repl_list = [6, 10, 18]
  
# Replace substring from Initial element
# Extracting index
idx = test_list.index(repl_list[0])
  
# Slicing till index, and then adding rest of list
res = test_list[ :idx] + repl_list + test_list[idx + len(repl_list):]
  
# printing result 
print("Substituted List : " + str(res))
输出 :
The original list : [5, 2, 6, 4, 7, 1, 3]
Substituted List : [5, 2, 6, 10, 18, 1, 3]