Python list operation

拜拜、爱过 提交于 2019-12-24 16:16:09

问题


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?


回答1:


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)



回答2:


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]



回答3:


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!



来源:https://stackoverflow.com/questions/16555921/python-list-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!