python的index函数,获取最后一个

Python013

python的index函数,获取最后一个,第1张

python的index函数可以获取列表中值的第一个索引

list= [1,2,3,4,5,1,2,2]

list.index(2) >>>>>>>>1

如果要获取相同值的最后一个索引

len(list) - list[::-1].index(2) - 1

反向取得list后,用list的长度减去反转后出现的第一个索引再减1

使用Here键。

Here是获取Python3中OrderedDict的最后一个键的方法.我需要在Python3中获取OrderedDict的最后一个值,而无需转换为列表.

Python 3.4.0 (default, Apr 11 2014, 13:05:11)

>>>from collections import OrderedDict

>>>dd = OrderedDict(a=1, b=2)

>>>next(reversed(dd))

'b'

>>>next(reversed(dd.keys()))

Traceback (most recent call last):

File "", line 1, in

TypeError: argument to reversed() must be a sequence

>>>next(reversed(dd.items()))

Traceback (most recent call last):

File "", line 1, in

TypeError: argument to reversed() must be a sequence

>>>next(reversed(dd.values()))

Traceback (most recent call last):

File "", line 1, in

TypeError: agument to reversed() must be a sequence