python - 根据索引列表中的索引获取项目列表
问题描述
我有一个名为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]
编辑以提供示例代码。
解决方案
我正在根据一些评论回答这个问题,因为当时由于我不清楚并且没有提供示例而被锁定。
我们可以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())
推荐阅读
- java - @Scheduled 方法不能使用存储库
- c# - 集合<>对象相等条件不起作用wpf c#
- javascript - React, Jest:模拟提交表单单元测试
- python - 这个 Python 表达式的输出是如何生成的?
- python - 如何添加具有多个变量的多个 if 条件
- azure - 将 Azure 触发的 WebJob 超时设置为无限
- java - 如何在不使用scriptlet的情况下使用JSP读取表单参数数据
- r - 有什么解决方法可以使用“tidyr”或“dplyr”对非表格数据进行年度统计?
- c# - 如何将我的 Visual Studio 2012 从 .NET Framework 4.5 升级到 .NET Framework 4.7.2?
- java - Spring Boot 自动配置 - 覆盖自动配置的 bean