了解切片

新手上路,请多包涵

我需要一个关于 Python 切片的很好的解释(参考是一个加号)。

原文由 Simon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 639
2 个回答

语法是:

 a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

还有 step 值,可以与上述任何一种一起使用:

 a[start:stop:step] # start through not past stop, by step

要记住的关键点是 :stop 值表示 不在 所选切片中的第一个值。因此, stopstart 之间的差异是所选元素的数量(如果 step 为 1,则默认值)。

另一个特点是 startstop 可能是 _负数_,这意味着它从数组的末尾而不是开头开始计数。所以:

 a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

同样, step 可能是一个负数:

 a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

如果项目比你要求的少,Python 对程序员很友好。例如,如果您要求 a[:-2]a 仅包含一个元素,您会得到一个空列表而不是错误。有时您更喜欢错误,因此您必须意识到这可能会发生。

slice 对象的关系

一个 slice 对象 可以代表一个切片操作,即:

 a[start:stop:step]

相当于:

 a[slice(start, stop, step)]

根据参数的数量,切片对象的行为也略有不同,类似于 range() ,即支持 slice(stop)slice(start, stop[, step]) 。 To skip specifying a given argument, one might use None , so that eg a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)]

虽然基于 : 的符号对简单切片非常有帮助,但显式使用 slice() 对象简化了切片的编程生成。

原文由 Greg Hewgill 发布,翻译遵循 CC BY-SA 4.0 许可协议

Python 教程 对此进行了讨论(向下滚动一点,直到您到达有关切片的部分)。

ASCII 艺术图也有助于记住切片的工作原理:

  +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

记住切片如何工作的一种方法是将索引视为字符 之间 的指向,第一个字符的左边缘编号为 0。然后 n 个 字符的字符串的最后一个字符的右边缘具有索引 n

原文由 Hans Nowak 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏