问题
A not too difficult question, I hope, from a beginner in Python.
I have a main list, listA, and I need to zero out items in that list based on values in an index list, listB.
So, for example, given:
listA = [10, 12, 3, 8, 9, 17, 3, 7, 2, 8]
listB = [1, 4, 8, 9]
the output I want is
listC = [10, 0, 3, 8, 0, 17, 3, 7, 0, 0]
This question [1] seems similar, but asked for the elements to be removed, not changed. I'm not sure if a similar approach is needed, but if so I can't see how to apply it.
[1] how to remove elements from one list if other list contain the indexes of the elements to be removed
回答1:
As a list comprehension:
listC = [value if index not in listB else 0 for index, value in enumerate(listA)]
Which for large lists can be improved substantially by using a set
for listB:
setB = set(listB)
listC = [value if index not in setB else 0 for index, value in enumerate(listA)]
Or copy the list and modify it, which is both faster and more readable:
listC = listA[:]
for index in listB:
listC[index] = 0
回答2:
You can use a list comprehension, enumerate, and a conditional expression:
>>> listA = [10, 12, 3, 8, 9, 17, 3, 7, 2, 8]
>>> listB = [1, 4, 8, 9]
>>>
>>> list(enumerate(listA)) # Just to demonstrate
[(0, 10), (1, 12), (2, 3), (3, 8), (4, 9), (5, 17), (6, 3), (7, 7), (8, 2), (9, 8)]
>>>
>>> listC = [0 if x in listB else y for x,y in enumerate(listA)]
>>> listC
[10, 0, 3, 8, 0, 17, 3, 7, 0, 0]
>>>
来源:https://stackoverflow.com/questions/23395945/update-list-elements-based-on-a-second-list-as-index