簡體   English   中英

根據 python 中的索引列表獲取列表中的元素

[英]getting elements in a list according to list of indices in python

我有一個索引列表,例如:

b=[0,2]  

和元素列表:

a = ['elem0','elem1','elem2'] 

我需要一個由 a 中的元素和ba索引組成的列表
(在本例中: ['elem0','elem2']

使用列表理解

[a[i] for i in b]

或者:

from operator import itemgetter

b=[0,2]
a = ['elem0','elem1','elem2']

print itemgetter(*b)(a)
>>> ('elem0','elem2')

使用列表理解 map 列表索引:

b=[0,2]
a = ['elem0','elem1','elem2'] 

sublist = [a[i] for i in b]
>ipython
In [1]: b=[0,2]
In [2]: a = ['elem0','elem1','elem2']
In [3]: [a[i] for i in b]
Out[3]: ['elem0', 'elem2']

如果您不知道,請在 python 手冊中查找“列表理解”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM