知行编程网知行编程网  2023-01-06 07:00 知行编程网 隐藏边栏  0 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python切片符号的使用的相关知识,希望可以帮到处于编程学习途中的小伙伴

python切片符号的使用

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

要记住的关键点是该:

1. 停止值表示第一个不在所选切片中的值。 stop 和 start 之间的区别是所选元素的数量(如果 step 为 1,则为默认值)。

2.startorstop可以是负数,表示从数组末尾开始计数,而不是从头开始。

所以:

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 仅包含一个元素,你将得到一个空列表而不是错误。有时你宁愿犯错,所以你必须意识到这可能会发生。


本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享