回答

收藏

理解切片符号

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

我需要对 Python 切片符号解释得很好(参考文献是加分项)。
; r8 Y, t9 U5 L7 o对我来说,这个符号需要一点掌握。. B0 F5 L, Q4 I1 i( n
它看起来很强大,但我还没有完全理解它。
+ |% K$ N( a1 t3 G- M2 X                                                                9 t+ N- E# i" O1 E% r; Q, @* h5 ?! R
    解决方案:                                                               
1 @% E% w% s% l" F4 m                                                                真的很简单:
* [5 ]7 ?" k$ Ja[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 V! V' {% z* c3 W) Z$ K& G
a[start:stop:step] # start through not past stop,by step要记住的关键点是:stop值不是所选切片中的第一值。因此,两者之间的差异stop和start是选择的元素的数量(如果step是1,默认值)。( i. a+ Q3 D2 J' t8 I: m
另一个特点是start或者stop这可能是一个负数,这意味着它从数组的末端而不是开始计数。
8 L/ |+ P# a0 Na[-1]    # last item in the arraya[-2:]   # last two items in the arraya[:-2]   # everything except the last two items同样,step可能是负:. j1 k1 _& a) S
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只有一个元素,你会得到一个空列表而不是错误。有时你更喜欢错误,所以你必须意识到这可能会发生。
# V. J1 ^" K2 s. b与slice()对象关系6 N( |/ L2 r2 I' w+ o6 p. @
切片操作符[]实际上是在上述代码中slice()使用:符号对象(仅在 内有效[]),即:& e4 I1 k% d, O
a[start:stop:step]相当于:
8 v8 Q; C% d+ g* Q% M" ha[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)]。
2 O" g" O6 [% j9 c3 u# p/ a2 \- |( G虽然:基于-符号对简单的切片很有帮助,但是slice()对象的显式使用简化了切片的编程生成。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则