Python中的负索引 [英] Negative indexing in Python

查看:313
本文介绍了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.

这篇关于Python中的负索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆