导语:
本文主要介绍了关于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电脑。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ 如何避免python输出中的空格08/28
- ♥ 什么是 python poc11/08
- ♥ Python中如何根据日期判断星期几09/01
- ♥ 如何在python中自定义一个函数11/26
- ♥ 什么是python中的面向对象11/24
- ♥ python如何判断none11/11
内容反馈