Python|用列表中的其他替换子列表
有时,在使用Python时,我们可能会遇到一个问题,即我们需要以一种需要将子列表替换为其他列表的方式来操作列表。这种问题在Web开发领域很常见。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环(当给定子列表时)
在我们知道要替换的子列表的情况下使用此方法。我们使用循环和列表切片来执行此任务,并划分查找需要首先操作的索引然后执行替换的逻辑。
# Python3 code to demonstrate working of
# Replace sublist with other in list
# Using loop (when sublist is given)
# helper function to find elements
def find_sub_idx(test_list, repl_list, start = 0):
length = len(repl_list)
for idx in range(start, len(test_list)):
if test_list[idx : idx + length] == repl_list:
return idx, idx + length
# helper function to perform final task
def replace_sub(test_list, repl_list, new_list):
length = len(new_list)
idx = 0
for start, end in iter(lambda: find_sub_idx(test_list, repl_list, idx), None):
test_list[start : end] = new_list
idx = start + length
# initializing list
test_list = [4, 5, 6, 7, 10, 2]
# printing original list
print("The original list is : " + str(test_list))
# Replace list
repl_list = [5, 6, 7]
new_list = [11, 1]
# Replace sublist with other in list
# Using loop (when sublist is given)
replace_sub(test_list, repl_list, new_list)
# printing result
print("List after replacing sublist : " + str(test_list))
输出 :
The original list is : [4, 5, 6, 7, 10, 2]
List after replacing sublist : [4, 11, 1, 10, 2]
方法#2:使用列表切片(当给定子列表索引时)
当我们只需要在可用的开始和结束索引上替换一个基本的子列表并且列表切片在这种情况下足以解决这个问题时,这个任务就变得更容易了。
# Python3 code to demonstrate working of
# Replace sublist with other in list
# Using list slicing ( When sublist index is given )
# initializing list
test_list = [4, 5, 6, 7, 10, 2]
# printing original list
print("The original list is : " + str(test_list))
# Replace list
repl_list_strt_idx = 1
repl_list_end_idx = 4
new_list = [11, 1]
# Replace sublist with other in list
# Using list slicing ( When sublist index is given )
test_list[repl_list_strt_idx : repl_list_end_idx] = new_list
# printing result
print("List after replacing sublist : " + str(test_list))
输出 :
The original list is : [4, 5, 6, 7, 10, 2]
List after replacing sublist : [4, 11, 1, 10, 2]