我需要从给定列表中选择一些元素,知道它们的索引.假设我想创建一个新列表,其中包含来自给定列表 [-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.
这篇关于访问列表的多个元素知道它们的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!