python的负索引,Python中的负索引

I have one record in a list

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

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

I use the below command:

>>> 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'

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

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值