首页 > 解决方案 > 根据索引列表中的索引获取项目列表

问题描述

我有一个名为a. 我有一个名为的索引列表b

如何将a带有索引的所有元素设置b为 0 ?

在我可以做的其他语言中a[b] = 0,这会返回错误TypeError: list indices must be integers or slices, not list,我不确定完成此操作的有效 pythonic 方式是什么。

两者都a可能b相当大。

#we are given this:
a = [2,4,6,8,10,12,14,16,18,20]#some list
b = [2,3,6,9]#some set of indices

#we aim to get this:
c = [6,8,14,20]

编辑以提供示例代码。

标签: pythonlist

解决方案


我正在根据一些评论回答这个问题,因为当时由于我不清楚并且没有提供示例而被锁定。

我们可以c根据需要使用列表理解:

#Solution 1, use list comprehension
c = [a[i] for i in b]
print(c)

或麻木:

#Solution 2, convert to numpy
a = np.array(a)
c = a[b]
print(c.tolist())

推荐阅读