开发者

slice operator understanding [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

good primer for python slice notation

I am a little confused as to what the slic开发者_JS百科e 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜