栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Understanding slice notation

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Understanding slice notation

真的很简单:

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

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

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

要记住的关键点是,该

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

另一个功能是

start
stop
可能是负数,这意味着它从数组的末尾而不是开头开始计数。所以:

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

同样,step可能为负数:

a[::-1]    # all items in the array, reverseda[1::-1]   # the first two items, reverseda[:-3:-1]  # the last two items, reverseda[-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])
支持。要跳过指定给定参数的操作,可以使用
None
,例如
a[start:]
等于
a[slice(start, None)]
a[::-1]
等于
a[slice(None, None, -1)]

尽管:基于的符号对于简单切片非常有帮助,但是

slice()
对象的显式使用简化了切片的程序生成。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617250.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号