Python - 用其他列表中的元素替换索引元素
有时,在处理Python数据时,我们可能会遇到一个问题,即我们有两个列表,我们需要用另一个列表中的实际元素替换一个列表中的位置。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
这是解决此问题的一种方法。在这种情况下,我们只是遍历列表并将索引值从一个列表分配给另一个。
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
# printing result
print ("The lists after index elements replacements is : " + str(res))
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’, ‘Gfg’]
方法 #2:使用map()
+ lambda
上述功能的组合可用于执行此任务。在此,我们使用 map() 和 lambda 函数对每个元素执行逻辑扩展任务。
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using map() + lambda
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using map() + lambda
res = list(map(lambda idx: test_list1[idx], test_list2))
# printing result
print ("The lists after index elements replacements is : " + str(res))
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’, ‘Gfg’]