Access multiple elements of list knowing their index(访问列表的多个元素知道它们的索引)
问题描述
我需要从给定列表中选择一些元素,知道它们的索引.假设我想创建一个新列表,其中包含来自给定列表 [-2, 1, 5, 3, 8, 5, 6] 的索引为 1、2、5 的元素.我所做的是:
I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
有没有更好的方法呢?类似 c = a[b] 的东西?
Is there any better way to do it? something like c = a[b] ?
推荐答案
你可以使用 operator.itemgetter
:
You can use operator.itemgetter
:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
或者你可以使用 numpy:
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]
<小时>
但实际上,您当前的解决方案很好.它可能是所有这些中最整洁的.
But really, your current solution is fine. It's probably the neatest out of all of them.
这篇关于访问列表的多个元素知道它们的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:访问列表的多个元素知道它们的索引


- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01