I have two lists ListA and ListB as follow:

ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']

I am trying to come up with List C which has the same length as List A but replace the numbers in the List A with 'X' if the number is in the List B.The result i am expecting:

ListC=['X','X','2','2','2','3','4','4','X','X','X','X']

FYI, length of ListB will always less than the length of ListA and ListB will not hold any numbers that is not in List A.

I have tried like this:

ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']
ListC=[]
for items in ListB:
    for a in ListA:
        if items==a:
            ListC.append('X')
        else:
            ListC.append(a)

obviously this will create a List that has (length of listB X lenght A) rather than just just the length of list A. Is there any built in function that does this operation? Could anyone give me a clue how to do it?

有帮助吗?

解决方案

You can use a list comprehension:

[i if i not in ListB else 'X' for i in ListA]

To fix your current code, use in to check to see if the item is in ListB:

for item in ListA:
    if item in ListB:
        ListC.append('X')
    else:
        ListC.append(item)

其他提示

Any time you are doing membership tests over and over on the same list, it's a good idea to create a set. Although it takes some time to construct the set the individual lookups can be much faster

SetB = set(ListB)
[i if i not in SetB else 'X' for i in ListA]

List Comprehension is your friend on this one:

ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']
ListC = [i if i not in ListB else 'x' for i in ListA]

--> ['x', 'x', '2', '2', '2', '3', '4', '4', 'x', 'x', 'x', 'x']

Hope this helps!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top