Python:如果元素在一个列表中,则更改其他元素? [英] Python: if element in one list, change element in other?
问题描述
我有两个列表(长度不同).在整个程序中,一个更改( list1
),另一个(较长)不更改( list2
).基本上,我有一个函数应该比较两个列表中的元素,并且如果 list1
中的元素在 list2
中,则该元素在 list2的副本中
更改为"A",副本中的所有其他元素都更改为"B".当 list1
中只有一个元素时,我可以使它工作.但是由于某种原因,如果列表较长,则 list2
中的所有元素都将变为B....
I have two lists (of different lengths). One changes throughout the program (list1
), the other (longer) doesn't (list2
). Basically I have a function that is supposed to compare the elements in both lists, and if an element in list1
is in list2
, that element in a copy of list2
is changed to 'A', and all other elements in the copy are changed to 'B'. I can get it to work when there is only one element in list1
. But for some reason if the list is longer, all the elements in list2
turn to B....
def newList(list1,list2):
newList= list2[:]
for i in range(len(list2)):
for element in list1:
if element==newList[i]:
newList[i]='A'
else:
newList[i]='B'
return newList
推荐答案
尝试一下:
newlist = ['A' if x in list1 else 'B' for x in list2]
适用于以下示例,希望我正确理解了吗?如果 B
中的值存在于 A
中,则插入'A'
,否则将'B'
插入新列表?
Works for the following example, I hope I understood you correctly? If a value in B
exists in A
, insert 'A'
otherwise insert 'B'
into a new list?
>>> a = [1,2,3,4,5]
>>> b = [1,3,4,6]
>>> ['A' if x in a else 'B' for x in b]
['A', 'A', 'A', 'B']
这篇关于Python:如果元素在一个列表中,则更改其他元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!