Getting all the min elements and its indices from a list

前端 未结 2 887
执笔经年
执笔经年 2020-12-17 01:19

I have a list that has a minimum element that is present multiple times like

a = [1,2,1,1,4,5,6]

And I want Python to return the element

相关标签:
2条回答
  • 2020-12-17 01:40

    I'd just do it like this:

    minimum = min(a)
    indices = [i for i, v in enumerate(a) if v == minimum]
    
    0 讨论(0)
  • 2020-12-17 01:44

    determine the minimum element, and then check it against other elements in the list.

    def locate_min(a):
        smallest = min(a)
        return smallest, [index for index, element in enumerate(a) 
                          if smallest == element]
    

    which will return a tuple (min_element, [location, location, ...]). If I understand you correctly, this is what I think you want. For you example:

    >>> locate_min([1, 2, 1, 1, 4, 5, 6])
    (1, [0, 2, 3])
    

    This example uses a list comprehension. If you're not familiar with this, it's roughly equivalent to the following for-loop version. (use the first version, this is just to help your understanding of how it works)

    def locate_min(a):
        min_indicies = []
        smallest = min(a)
        for index, element in enumerate(a):
                if smallest == element: # check if this element is the minimum_value
                        min_indicies.append(index) # add the index to the list if it is
    
        return smallest, min_indicies
    
    0 讨论(0)
提交回复
热议问题