2012-08-07 68 views
26

在Python中,我有一个元素列表aList和索引列表myIndices。有没有什么办法可以一次检索到aList中的那些项目,其索引值为myIndicesPython:按索引过滤列表

例子:

>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
>>> myIndices = [0, 3, 4] 
>>> aList.A_FUNCTION(myIndices) 
['a', 'd', 'e'] 
+7

'[为我ALIST [i]于myIndi​​ces]' – Morwenn 2012-08-07 13:52:29

+3

如果你只想迭代的元素,我建议使用生成器表达式替代:'(aList [i] for myIndIndices)' – hochl 2012-08-07 14:28:18

回答

52

我不知道有什么方法来做到这一点。但是,你可以使用一个list comprehension

>>> [aList[i] for i in myIndices] 
9

肯定使用列表理解,但这里是做它的功能(有没有list方法是做到这一点)。然而,这不利于itemgetter,但仅仅是为了我所发布的知识。

>>> from operator import itemgetter 
>>> a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
>>> my_indices = [0, 3, 4] 
>>> itemgetter(*my_indices)(a_list) 
('a', 'd', 'e') 
+0

我相信这不是正确的情况使用'itemgetter'。 – 2012-08-07 14:08:32

+0

@BasicWolf是的,你不应该使用它,但OP要求一个功能,可以做到这一点,所以我只是显示它是什么。我会更明确地说你不应该使用它。 – jamylak 2012-08-07 14:09:48

+0

我认为这也将受限于函数可以拥有的最大参数数量的限制。 – Paddy3118 2012-08-07 18:34:56

5

通过列表索引可以在numpy中完成。你的基地列表转换为numpy的数组,然后应用其他列表作为索引:

>>> from numpy import array 
>>> array(aList)[myIndices] 
array(['a', 'd', 'e'], 
    dtype='|S1') 

如果需要,转换回列表结尾:

>>> from numpy import array 
>>> a = array(aList)[myIndices] 
>>> list(a) 
['a', 'd', 'e'] 

在某些情况下,这种解决方案可以比列表理解更方便。

1

我却高兴不起来这些解决方案,所以我创建了一个Flexlist类,简单地扩展了list类,并允许灵活的索引由整数,切片或索引列表:

class Flexlist(list): 
    def __getitem__(self, keys): 
     if isinstance(keys, (int, slice)): return list.__getitem__(self, keys) 
     return [self[k] for k in keys] 

然后,你的榜样,您可以用使用它:

aList = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g']) 
myIndices = [0, 3, 4] 
vals = aList[myIndices] 

print(vals) # ['a', 'd', 'e'] 
+0

这非常有用。 – mikeTronix 2017-09-01 20:07:26

4

你可以使用map

map(aList.__getitem__, myIndices) 

operator.itemgetter

f = operator.itemgetter(*aList) 
f(myIndices) 
2

如果你不需要与所有元素同时访问列表,而只是希望使用在子列表迭代的所有项目(或它们传递的东西,会),更有效地使用发电机的表达,而不是名单理解它:

(aList[i] for i in myIndices)