Python: filtering lists by indices

后端 未结 7 1118
情深已故
情深已故 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: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']
    

提交回复
热议问题