下面是一个示例代码,演示了如何遍历两个列表,如果找到匹配的值则进行替换:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
replacement_dict = {4: 10, 5: 20}
for i in range(len(list1)):
if list1[i] in replacement_dict:
list1[i] = replacement_dict[list1[i]]
for i in range(len(list2)):
if list2[i] in replacement_dict:
list2[i] = replacement_dict[list2[i]]
print(list1) # 输出: [1, 2, 3, 10, 20]
print(list2) # 输出: [10, 20, 6, 7, 8]
在这个示例中,我们有两个列表list1
和list2
,以及一个替换字典replacement_dict
。我们使用for
循环遍历列表中的每个元素,并检查该元素是否存在于替换字典中。如果存在,则将列表中的元素替换为替换字典中对应的值。
最后,我们打印更新后的列表list1
和list2
。注意,在这个示例中,我们直接修改了原始列表,所以无需使用额外的变量来存储结果。
下一篇:遍历两个年份之间的每个月