slice operator understanding

Possible Duplicate:
good primer for python slice notation

I am a little confused as to what the slice operator does in python. Can anyone explain to me how it works?


The slice operator is a way to get items from lists, as well as change them. See http://docs.python.org/tutorial/introduction.html#lists.

You can use it to get parts of lists, skipping items, reversing lists, and so on:

>>> a = [1,2,3,4]
>>> a[0:2] # take items 0-2, upper bound noninclusive
[1, 2]
>>> a[0:-1] #take all but the last
[1, 2, 3]
>>> a[1:4]
[2, 3, 4]
>>> a[::-1] # reverse the list
[4, 3, 2, 1]
>>> a[::2] # skip 2
[1, 3]

The first index is where to start, the (optional) second one is where to end, and the (optional) third one is the step.

And yes, this question is a duplicate of Explain Python's slice notation.

链接地址: http://www.djcxy.com/p/26746.html

上一篇: python中[:]的含义是什么?

下一篇: 切片操作员理解