Python:按索引过滤列表

Ric*_*son 41 python indexing list filter

在Python中,我有一个元素aList列表和一个索引列表myIndices.有什么方法可以一次性检索所有项目中aList的值作为索引myIndices吗?

例:

>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> myIndices = [0, 3, 4]
>>> aList.A_FUNCTION(myIndices)
['a', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)

Val*_*ior 72

我不知道有任何方法可以做到这一点.但你可以使用列表理解:

>>> [aList[i] for i in myIndices]
Run Code Online (Sandbox Code Playgroud)


jam*_*lak 11

绝对使用列表理解,但这是一个执行它的函数(没有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')
Run Code Online (Sandbox Code Playgroud)


Mar*_*ski 7

按列表编制索引可以在numpy中完成.将基本列表转换为numpy数组,然后将另一个列表应用为索引:

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

如果需要,请在最后转换回列表:

>>> from numpy import array
>>> a = array(aList)[myIndices]
>>> list(a)
['a', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)

在某些情况下,此解决方案可能比列表理解更方便.


wen*_*zul 5

你可以用 map

map(aList.__getitem__, myIndices)
Run Code Online (Sandbox Code Playgroud)

要么 operator.itemgetter

f = operator.itemgetter(*aList)
f(myIndices)
Run Code Online (Sandbox Code Playgroud)


kab*_*hya 5

或者,您可以使用maplambda函数来采用函数式方法。

>>> list(map(lambda i: aList[i], myIndices))
['a', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)