根据第二个列表作为索引更新列表元素
这是一个不太难的问题,我希望能帮助到一个Python初学者。
我有一个主列表,叫做listA,我需要根据另一个索引列表listB中的值,把listA中的某些项变成零。
举个例子,假设有:
listA = [10, 12, 3, 8, 9, 17, 3, 7, 2, 8]
listB = [1, 4, 8, 9]
我想要的输出是
listC = [10, 0, 3, 8, 0, 17, 3, 7, 0, 0]
这个问题[1]看起来有点相似,但它是问如何删除元素,而不是修改。我不太确定是否需要用类似的方法,但如果需要的话,我不知道该怎么应用。
2 个回答
4
你可以使用一种叫做 列表推导式,还有 enumerate
函数,以及一种叫做 条件表达式 的东西:
>>> 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]
>>>
3
作为一种列表推导式:
listC = [value if index not in listB else 0 for index, value in enumerate(listA)]
对于很大的列表,可以通过使用一个 set
来显著提高 listB 的性能:
setB = set(listB)
listC = [value if index not in setB else 0 for index, value in enumerate(listA)]
或者复制这个列表并进行修改,这样做既更快又更容易理解:
listC = listA[:]
for index in listB:
listC[index] = 0