Python: finding the last index of a min element?

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

has min element 1, but it is last seen with index 4.

+7
python list min
source share
6 answers
a = [1,2,3,4,1,2] a.reverse() print len(a) - a.index(min(a)) - 1 

Update after comment:

A side effect can be removed by contacting again (but, of course, this is pretty inefficient).

 a.reverse() 
+3
source share
 >>> values = [1,2,3,4,1,2] >>> -min((x, -i) for i, x in enumerate(values))[1] 4 

There are no changes in the original list, it works for arbitrary iterations and only one pass is required.

This creates iterable tuples with the first value being the source element from the list, and the second being the negative index. When looking for a minimum in this iterable tuple, values ​​and then indexes will be compared first, so you get a tuple (min_value, lower_negative_index). By extracting the second element from this tuple and denying it again, you get the highest minimum value index.

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

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

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

+11
source share

len(list_) - list_[::-1].index(min(list_)) - 1

Get the length of the list, subtract from this index the min of the list in the reverse list, and then subtract 1.

+3
source share

Not as efficient (I'm new to Python), but works great. Idx will just hold the last index of the minimum element. I think the M. Keysers method is the best.

 array = [1,2,3,4,1,2] min_val = min(array) for i in range(len(array)): if array[i] == min_val: idx = i print idx 
+2
source share
 >>> from operator import itemgetter >>> from itertools import izip,count >>> min(izip(count(len(L)-1,-1), reversed(L)), key=itemgetter(1))[0] 4 

Explanation

reversed returns an iterator that goes through the source list without creating a temporary list:

 >>> reversed(L) <listreverseiterator object at 0x00E823B0> 

izip and count are lazy, and bytecode doesn't seem to be executing, so I expect this solution to be pretty fast and single-line.


Time comparison

http://ideone.com/ZQuge3

Decisions using index turned out to be the fastest, despite the fact that they have to do 2 passes over the list. Other solutions create helper tuples inside the generators at each iteration, and I think that is the reason these solutions are slower. Even the akson128 solution, which causes the byte code to execute, is even faster (because it does not need to create tuples).

+2
source share
 len(myList)-1 - myList[::-1].index(min(list)) 

The slice list[::-1] notation is used to return a shallow copy of the inverted list so that it does not change your original list and then looks for the minimum value in this list

 >>>myList = [1,2,3,4,1,2] >>>len(myList)-1 - myList[::-1].index(min(list)) 4 
+2
source share

All Articles