问题
In python, if I have a list say [2,1,1,3,5], then is it possible to get
[2,1,1,3,5].index(1) as 2 i.e first match starting from the higher end instead of the lower?
回答1:
Can't say I've ever needed to do this, but you could always hack it with:
lst = [2,1,1]
reverseindex = len(lst)-1 - lst[::-1].index(1)
Note that if you had a STRING, you could do:
string = "21135"
reverseindex = string.rindex(1)
# reverseindex == 2
But lists don't have this function.
回答2:
If you don't care about list order being preserved, you could always use lst.reverse() before lst.index(1).
Documentation is on the official site
来源:https://stackoverflow.com/questions/22793248/python-list-index-from-end-of-the-list