在Python中,我有一個元素列表aList
和索引列表myIndices
。有沒有什麼辦法可以一次檢索到aList
中的那些項目,其索引值爲myIndices
?Python:按索引過濾列表
例子:
>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> myIndices = [0, 3, 4]
>>> aList.A_FUNCTION(myIndices)
['a', 'd', 'e']
在Python中,我有一個元素列表aList
和索引列表myIndices
。有沒有什麼辦法可以一次檢索到aList
中的那些項目,其索引值爲myIndices
?Python:按索引過濾列表
例子:
>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> myIndices = [0, 3, 4]
>>> aList.A_FUNCTION(myIndices)
['a', 'd', 'e']
我不知道有什麼方法來做到這一點。但是,你可以使用一個list comprehension:
>>> [aList[i] for i in myIndices]
肯定使用列表理解,但這裏是做它的功能(有沒有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')
通過列表索引可以在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']
在某些情況下,這種解決方案可以比列表理解更方便。
我卻高興不起來這些解決方案,所以我創建了一個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']
這非常有用。 – mikeTronix 2017-09-01 20:07:26
你可以使用map
map(aList.__getitem__, myIndices)
或operator.itemgetter
f = operator.itemgetter(*aList)
f(myIndices)
如果你不需要與所有元素同時訪問列表,而只是希望使用在子列表迭代的所有項目(或它們傳遞的東西,會),更有效地使用發電機的表達,而不是名單理解它:
(aList[i] for i in myIndices)
'[爲我ALIST [i]於myIndices]' – Morwenn 2012-08-07 13:52:29
如果你只想迭代的元素,我建議使用生成器表達式替代:'(aList [i] for myIndIndices)' – hochl 2012-08-07 14:28:18