知道其索引的多个列表元素 [英] Access multiple elements of list knowing their index

查看:78
本文介绍了知道其索引的多个列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从给定列表中选择一些元素,知道它们的索引。假设我想创建一个新列表,其中包含索引为1,2,5的元素,来自给定列表[-2,1,5,3,8,5,6]。我做的是:

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.

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

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