基于第二个列表作为索引更新列表元素 [英] Update list elements based on a second list as index

查看:53
本文介绍了基于第二个列表作为索引更新列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对Python初学者来说这不是一个太困难的问题.

A not too difficult question, I hope, from a beginner in Python.

我有一个主列表listA,我需要根据索引列表listB中的值将该列表中的项目清零.

I have a main list, listA, and I need to zero out items in that list based on values in an index list, listB.

例如,给定:

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]似乎很相似,但是要求删除而不是更改元素.我不确定是否需要类似的方法,但是如果这样,我看不到如何应用.

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] 推荐答案

作为列表理解:

listC = [value if index not in listB else 0 for index, value in enumerate(listA)]

通过使用listB的 set 可以大大改善大型列表的哪些地方:

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

这篇关于基于第二个列表作为索引更新列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆