2012-08-07 56 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)