Python中的负索引

问题描述:

我在列表中有一条记录

>>> bob =['bob smith',42,30000,'software']

我正试图从该记录中获取姓氏"smith"

I am trying to get the last name 'smith' from this record

我使用以下命令:

>>> bob[0].split()[1]

它为我提供了史密斯"

It provides me 'smith'

但是我要指的书使用以下命令:

But the book I am referring to use the below command:

>>> bob[0].split()[-1]

它也给我同样的结果'史密斯'

it also gives me same result 'smith'

为什么索引[1]和[-1]提供相同的结果?

Why do indexes [1] and [-1] provide the same result?

可以使用负索引对Python列表进行反向索引". -1表示最后一个元素,-2表示倒数第二个,依此类推.碰巧的是,在长度2的列表中,最后一个元素也是索引为1的元素.

Python lists can be "back indexed" using negative indices. -1 signifies the last element, -2 signifies the second to last and so on. It just so happens that in your list of length 2, the last element is also the element at index 1.

您的书建议使用-1,因为从逻辑角度来看它更合适.您不希望索引本身为1项目,而是列表的 last元素,这是姓氏.例如,如果还包括中间名怎么办?然后,使用1的索引将不起作用,而使用-1的索引将是无效的.

Your book suggests using -1 because it is more appropriate from a logical standpoint. You don't want the item at index 1 per se, but rather the last element of the list, which is the last name. What if, for example, a middle name was also included? Then using an index of 1 would not work whereas an index of -1 would.