📜  Python – 替换列表的前缀部分

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

Python – 替换列表的前缀部分

给定 2 个列表,将一个列表替换为另一个列表的前缀元素。

方法 #1:使用 len() + 列表切片

在此,我们使用 len() 和列表切片在列表 1 的大小之后添加列表 1 和列表 2 的一部分。

Python3
# Python3 code to demonstrate working of
# Substitute prefix part of List
# Using len() + list slicing
 
# initializing lists
test_list1 = [4, 6, 8, 7]
test_list2 = [2, 7, 9, 4, 2, 8, 6, 4, 1, 10]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# size slicing after length of list 1
res = test_list1 + test_list2[len(test_list1) : ]
 
# printing result
print("The joined list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Substitute prefix part of List
# Using * operator
 
# initializing lists
test_list1 = [4, 6, 8, 7]
test_list2 = [2, 7, 9, 4, 2, 8, 6, 4, 1, 10]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# * operator reconstructs lists
res = [*test_list1, *test_list2[len(test_list1) : ]]
 
# printing result
print("The joined list : " + str(res))


输出
The original list 1 : [4, 6, 8, 7]
The original list 2 : [2, 7, 9, 4, 2, 8, 6, 4, 1, 10]
The joined list : [4, 6, 8, 7, 2, 8, 6, 4, 1, 10]

方法 #2:使用 *运算符

在此,我们使用 *运算符执行打包和解包到新列表的任务。

Python3

# Python3 code to demonstrate working of
# Substitute prefix part of List
# Using * operator
 
# initializing lists
test_list1 = [4, 6, 8, 7]
test_list2 = [2, 7, 9, 4, 2, 8, 6, 4, 1, 10]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# * operator reconstructs lists
res = [*test_list1, *test_list2[len(test_list1) : ]]
 
# printing result
print("The joined list : " + str(res))
输出
The original list 1 : [4, 6, 8, 7]
The original list 2 : [2, 7, 9, 4, 2, 8, 6, 4, 1, 10]
The joined list : [4, 6, 8, 7, 2, 8, 6, 4, 1, 10]