Finding the index of elements based on a condition using python list comprehension

前端 未结 5 2037
谎友^
谎友^ 2020-11-28 02:53

The following Python code appears to be very long winded when coming from a Matlab background

>>> a = [1, 2, 3, 1, 2, 3]
>>> [index for ind         


        
5条回答
  •  执念已碎
    2020-11-28 03:42

    Even if it's a late answer: I think this is still a very good question and IMHO Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access the indices of list elements according to a manually defined filter.

    You could manually define a function, which provides that functionality:

    def indices(list, filtr=lambda x: bool(x)):
        return [i for i,x in enumerate(list) if filtr(x)]
    
    print(indices([1,0,3,5,1], lambda x: x==1))
    

    Yields: [0, 4]

    In my imagination the perfect way would be making a child class of list and adding the indices function as class method. In this way only the filter method would be needed:

    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
        def indices(self, filtr=lambda x: bool(x)):
            return [i for i,x in enumerate(self) if filtr(x)]
    
    my_list = MyList([1,0,3,5,1])
    my_list.indices(lambda x: x==1)
    

    I elaborated a bit more on that topic here: http://tinyurl.com/jajrr87

提交回复
热议问题