Python list.index() from end of the list

无人久伴 提交于 2021-01-28 08:37:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!