Python: filtering lists by indices

后端 未结 7 1089
情深已故
情深已故 2020-12-01 11:56

In Python I have a list of elements aList and a list of indices myIndices. Is there any way I can retrieve all at once those items in aList

7条回答
  •  攒了一身酷
    2020-12-01 12:31

    Indexing by lists can be done in numpy. Convert your base list to a numpy array and then apply another list as an index:

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

    If you need, convert back to a list at the end:

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

    In some cases this solution can be more convenient than list comprehension.

提交回复
热议问题