Python: Finding the last index of min element?

前端 未结 6 487
情书的邮戳
情书的邮戳 2021-01-12 05:20

For example [1,2,3,4,1,2]

has min element 1, but it occurs for the last time at index 4.

6条回答
  •  日久生厌
    2021-01-12 05:40

    >>> values = [1,2,3,4,1,2]
    >>> -min((x, -i) for i, x in enumerate(values))[1]
    4
    

    No modification to the original list, works for arbitrary iterables, and only requires one pass.

    This creates an iterable of tuples with the first value being the original element from the list, and the second element being the negated index. When finding the minimum in this iterable of tuples the values will be compared first and then the indices, so you will end up with a tuple of (min_value, lowest_negative_index). By taking the second element from this tuple and negating it again, you get the highest index of the minimum value.

    Here is an alternative version that is very similar, but uses a key function for min():

    >>> min(range(len(values)), key=lambda i: (values[i], -i))
    4
    

    Note that this version will only work for sequences (lists, tuples, strings etc.).

提交回复
热议问题