回答

收藏

理解切片符号

技术问答 技术问答 290 人阅读 | 0 人回复 | 2023-09-11

我需要对 Python 切片符号解释得很好(参考文献是加分项)。
$ M8 i9 d; r5 a, U2 x. y1 ]5 r对我来说,这个符号需要一点掌握。! c7 {; ]2 u  P/ o* Z, c/ `
它看起来很强大,但我还没有完全理解它。# z1 c  H5 X, L" }6 ]+ A
                                                               
- {$ j3 x& N& C8 _# }    解决方案:                                                                . @* t/ y6 L/ G: Q# U& m- M
                                                                真的很简单:
4 T4 |1 N- a# s. D/ s/ k6 Ca[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值,可与上述任何一个一起使用:9 a6 b  X  t! F% h% b) a: x
a[start:stop:step] # start through not past stop,by step要记住的关键点是:stop值不是所选切片中的第一值。因此,两者之间的差异stop和start是选择的元素的数量(如果step是1,默认值)。1 }/ `- Z# a8 W) A' `' t; O/ i
另一个特点是start或者stop这可能是一个负数,这意味着它从数组的末端而不是开始计数。" A) z2 ?& g3 [( t
a[-1]    # last item in the arraya[-2:]   # last two items in the arraya[:-2]   # everything except the last two items同样,step可能是负:, R7 M+ ~/ v1 O( D& X5 O3 M
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只有一个元素,你会得到一个空列表而不是错误。有时你更喜欢错误,所以你必须意识到这可能会发生。% f* U1 h) Q% o1 k& t7 ~9 E
与slice()对象关系
( m; [' Y$ c. J0 V: r6 q6 l切片操作符[]实际上是在上述代码中slice()使用:符号对象(仅在 内有效[]),即:
# o  L5 N& ]- n. x9 L- \a[start:stop:step]相当于:! v% ~% Y; L6 w& t' @
a[slice(start,stop,step)]切片对象的性能也略有不同,这取决于参数的数量range(),即两个slice(stop)和slice(start,stop[,step])支持。可以使用指定的给定参数。None,以便 ega[start:]等价于a[slice(start,None)]或a[::-1]等价于a[slice(None,None,-1)]。) V6 U8 l) F6 S* h9 @
虽然:基于-符号对简单的切片很有帮助,但是slice()对象的显式使用简化了切片的编程生成。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则