简体   繁体   中英

Find last index of minimum and maximum elements in list python

Let's say I have this list:

A = [3, 4, 3, 5, 7, 665, 87, 665]

When I do A.index(min(A)) , I get 0 .

And, when I do A.index(max(A)) , I get 5 .

I am looking for a way to get the last index of the min and max element in the list. ie I want to get the answer as 2 in place of 0 for min number and 7 in place of 5 for max number

To get the index of last occurrence of element in the list , you can subtract the value of list.index(element) on reverse of the list from the length of list.

Below is the sample code to get the index of last highest and lowest number in the list:

>>> A = [3,4,3,5,7,665,87,665]

# For min. number
>>> len(A) - A[::-1].index(min(A)) - 1
2

# For max. number
>>> len(A) - A[::-1].index(max(A)) - 1
7

In the above code, A[::-1] will reverse the A list.

If you want the index of the last min or max in the list. So after getting the max or min loop through the list and find other numbers equal to the min or max. Every time your loop through the list makes sure your keep track of the current Index.

You can compute the minimum as well as the last index of the minimum value in one single loop through the list:

    last_idx = None
    min_value = None
    for idx, value in enumerate(l):
        if min_value is None or value <= min_value:
            last_idx = idx
            min_value = value

    print(last_idx)  # 2
    print(min_value)  # 3

Likewise, you can also compute all indices of the minimum value by storing the indices in a collection such as eg a set:

    idces = set()
    min_value = None
    for idx, value in enumerate(l):
        if min_value is None or value == min_value:
            idces.add(idx)
            min_value = value
        elif value < min_value:
            idces = {idx}
            min_value = value

    print(idces)  # {0, 2}
    print(min_value)  # 3

The case for the maximum is analogous, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM