Python 切片运算符理解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4486382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:58:39  来源:igfitidea点击:

slice operator understanding

python

提问by Ronnie

Possible Duplicate:
good primer for python slice notation

可能的重复:
python 切片符号的良好入门

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

我对切片运算符在 python 中的作用有点困惑。谁能向我解释它是如何工作的?

回答by li.davidm

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.

slice 运算符是一种从列表中获取项目以及更改它们的方法。请参阅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.

是的,这个问题是解释 Python 的切片符号的重复。