Skip to content Skip to sidebar Skip to footer

Update List Elements Based On A Second List As Index

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, f

Solution 1:

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 = [0if x in listB else y for x,y inenumerate(listA)]>>>listC
[10, 0, 3, 8, 0, 17, 3, 7, 0, 0]
>>>

Solution 2:

As a list comprehension:

listC = [value ifindexnot in listB else0forindex, 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[:]
forindex in listB:
    listC[index] = 0

Post a Comment for "Update List Elements Based On A Second List As Index"