简体   繁体   中英

Python: Finding the last index of min element?

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

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

>>> 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.).

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

获取列表的长度,从反向列表中的列表的min的索引中减去,然后减去1。

a = [1,2,3,4,1,2]

a.reverse()
print len(a) - a.index(min(a)) - 1

Update after comment:

The side effect can be removed by reversing again (but of course that is quite inefficient).

a.reverse()

Not so efficient (I'm a beginner in Python), but works fine as well. The idx will just hold the last index of minimum element. I think that M.Keijzers 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
>>> 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 iterator which goes through original list without creating temporary list:

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

izip and count are lazy, and there seems to be no byte-code execution, so I expect this solution to be pretty fast, and one-liner at that.


Time comparisons

http://ideone.com/ZQuge3

Solutions using index turned out to be fastest despite they have to make 2 passes over list. Other solutions create auxiliary tuples inside generators on each iteration and I think it is the reason why these solutions are slower. Even akson128's solution which invokes byte-code execution is still faster (because it doesn't have to create tuples).

len(myList)-1 - myList[::-1].index(min(list))

This uses the slice notation list[::-1] to return a shallow copy of a reversed list, so that it doesn't change your original list, then searches for the minimum value in that list

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

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