切片操作员理解

时间:2010-12-20 02:09:46

标签: python

  

可能重复:
  good primer for python slice notation

我对切片操作符在python中的作用有点困惑。任何人都可以向我解释它是如何工作的吗?

1 个答案:

答案 0 :(得分:6)

切片运算符是一种从列表中获取项目以及更改它们的方法。请参阅http://docs.python.org/tutorial/introduction.html#lists

您可以使用它来获取列表的一部分,跳过项目,撤消列表等等:

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

第一个索引是从哪里开始,(可选)第二个索引是在哪里结束,而(可选)第三个索引是步骤。

是的,这个问题与Explain Python's slice notation重复。

相关问题