我需要对 Python 切片符号解释得很好(参考文献是加分项)。 ) ]6 W& ~8 k1 n4 v7 ]+ k B" ^对我来说,这个符号需要一点掌握。 " C9 m9 L; I+ }1 \它看起来很强大,但我还没有完全理解它。) u! F; N. e- B+ @9 L7 ^! c
* }, p6 C$ j( \9 [0 G 解决方案: - V+ g2 v9 G D
真的很简单:3 o( D7 W1 \7 @% Q+ g
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值,可与上述任何一个一起使用:- q2 }+ K' y o$ l/ R, X$ q4 e! s
a[start:stop:step] # start through not past stop,by step要记住的关键点是:stop值不是所选切片中的第一值。因此,两者之间的差异stop和start是选择的元素的数量(如果step是1,默认值)。) f( x5 x6 h9 {/ P
另一个特点是start或者stop这可能是一个负数,这意味着它从数组的末端而不是开始计数。 + g- ?: o6 G7 I b" [a[-1] # last item in the arraya[-2:] # last two items in the arraya[:-2] # everything except the last two items同样,step可能是负: , p) h" ~# O0 E7 |' Ea[::-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只有一个元素,你会得到一个空列表而不是错误。有时你更喜欢错误,所以你必须意识到这可能会发生。6 S# U4 c- u8 Z
与slice()对象关系8 Y8 `( U; E% l) V
切片操作符[]实际上是在上述代码中slice()使用:符号对象(仅在 内有效[]),即: ' _9 N R2 y& Q, G, H: ma[start:stop:step]相当于:& i6 P1 v( W! {" ~$ F
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)]。 ) @/ l7 u9 k+ X# ~1 t虽然:基于-符号对简单的切片很有帮助,但是slice()对象的显式使用简化了切片的编程生成。