本文介绍了访问列表的多个元素知道它们的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我需要从给定列表中选择一些元素,知道它们的索引.假设我想创建一个新列表,其中包含来自给定列表 [-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.
这篇关于访问列表的多个元素知道它们的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)