Python - 从初始元素替换子列表
给定一个列表和替换子列表,根据替换子列表的初始元素执行列表子列表的替换。
Input : test_list = [3, 7, 5, 3], repl_list = [7, 8]
Output : [3, 7, 8, 3]
Explanation : Replacement starts at 7 hence 7 and 8 are replaced.
Input : test_list = [3, 7, 5, 3, 9, 10], repl_list = [5, 6, 7, 4]
Output : [3, 7, 5, 6, 7, 4]
Explanation : Replacement starts at 5 and goes till end of list.
方法:使用列表理解+列表切片
上述功能的组合可以用来解决这个问题。在此,我们提取开始元素的索引,然后根据需要对列表进行适当的切片。
# 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]