在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