负列表索引?

我试图理解下面这段代码:

# node list
n = []
for i in xrange(1, numnodes + 1):
tmp = session.newobject();
n.append(tmp)
link(n[0], n[-1])

具体来说,我不明白 -1指的是什么。如果索引 0指的是第一个元素,那么 -1指的是什么?

185514 次浏览

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.