Python: Finding the last index of min element?

前端 未结 6 482
情书的邮戳
情书的邮戳 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条回答
  •  旧时难觅i
    2021-01-12 05:40

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

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

提交回复
热议问题