Python: filtering lists by indices

后端 未结 7 1085
情深已故
情深已故 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:06

    If you do not require a list with simultaneous access to all elements, but just wish to use all the items in the sub-list iteratively (or pass them to something that will), its more efficient to use a generator expression rather than list comprehension:

    (aList[i] for i in myIndices) 
    
    0 讨论(0)
  • 2020-12-01 12:11

    I don't know any method to do it. But you could use a list comprehension:

    >>> [aList[i] for i in myIndices]
    
    0 讨论(0)
  • 2020-12-01 12:14

    Definitely use a list comprehension but here is a function that does it (there are no methods of list that do this). This is however bad use of itemgetter but just for the sake of knowledge I have posted this.

    >>> 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 讨论(0)
  • 2020-12-01 12:23

    I wasn't happy with these solutions, so I created a Flexlist class that simply extends the list class, and allows for flexible indexing by integer, slice or index-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]
    

    Then, for your example, you could use it with:

    aList = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
    myIndices = [0, 3, 4]
    vals = aList[myIndices]
    
    print(vals)  # ['a', 'd', 'e']
    
    0 讨论(0)
  • 2020-12-01 12:27

    You could use map

    map(aList.__getitem__, myIndices)
    

    or operator.itemgetter

    f = operator.itemgetter(*aList)
    f(myIndices)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题