当前位置: 首页 > 图灵资讯 > 行业资讯> python切片符号的使用

python切片符号的使用

发布时间:2024-06-30 20:33:25

a[start:stop]#itemsstartthroughstop-1
a[start:]#itemsstartthroughtherestofthearray
a[:stop]#itemsfromthebeginningthroughstop-1
a[:]#acopyofthewholearray

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

a[start:stop:step]#startthroughnotpaststop,bystep

要记住的关键点是:

1、stop值表示不是所选切片中的第一个值。stop和start之间的差异是所选元素的数量(如果step是1,则默认值)。

2、startorstop可能是负数,这意味着它从数组的末端而不是开始计数。

所以:

a[-1]#lastiteminthearray
a[-2:]#lasttwoitemsinthearray
a[:-2]#everythingexceptthelasttwoitems

同样,step也可能是负数:

a[::-1]#allitemsinthearray,reversed
a[1::-1]#thefirsttwoitems,reversed
a[:-3:-1]#thelasttwoitems,reversed
a[-3::-1]#everythingexceptthelasttwoitems,reversed

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

以上是python切片符号的使用,希望对大家有所帮助。更多Python学习指导:python基础教程

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

相关文章

如何让vim支持python3

如何让vim支持python3

2025-09-12
python2.7和3.6区别有哪些

python2.7和3.6区别有哪些

2025-09-12
python3有serial库吗

python3有serial库吗

2025-09-12
python中w、r表示什么意思

python中w、r表示什么意思

2025-09-12
python中如何把list变成字符串

python中如何把list变成字符串

2025-09-12
python命名空间是什么

python命名空间是什么

2025-09-12