Python列表,使用匹配索引更改匹配项的值

问题描述

如果我有

list1 = [1,2,3,6]
list2 = [4,5,6]

如何更改两个列表之间匹配的任何值?仅当索引也匹配

所需的输出

list1 = [1,'match']

我在用这个

for idx,x in enumerate(list1):
    if x in list2:  
        list1[idx] = 'match'

但这代替了3和6

解决方法

使用zip来同时迭代两个列表,并相互检查每个值,而不是使用in

list3 = ['match' if x == y else x for x,y in zip(list1,list2)]

常规格式为:

list3 = []
for x,list2):
    if x == y:
        list3.append(x)
    else:
        list3.append('match')
,

这里是获得相同结果的另一种方法:

list1 = ['match' if v == list2[k] else v for (k,v) in enumerate(list1)]
,

如果将两个列表都压缩在一起,则可以比较它们的项目-如果要保留原始列表,并且可能编写比列表理解少的混乱代码,则可以执行以下操作:

list1 = [1,2,3,6]
list2 = [4,5,6]

for i,t in enumerate(zip(list1,list2)):
    a,b = t  # unpack the tuple t
    if a == b:
       list1[i]="match"

最后,list1[1,'match']

,
list(map(lambda a,b: a if a != b else 'match',list1,list2))
[1,'match']