Update list elements based on a second list as index

家住魔仙堡 提交于 2021-02-10 14:06:56

问题


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

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