为了账号安全,请及时绑定邮箱和手机立即绑定

了解切片表示法

了解切片表示法

弑天下 2019-05-20 16:01:11
我需要在Python的切片表示法上有一个很好的解释(引用是一个加号)。对我来说,这种符号需要一点点提升。它看起来非常强大,但我还没有完全了解它。
查看完整描述

4 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

它非常简单:


a[start:stop]  # items start through stop-1

a[start:]      # items start through the rest of the array

a[:stop]       # items from the beginning through stop-1

a[:]           # 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 array

a[-2:]   # last two items in the array

a[:-2]   # everything except the last two items

同样,step可能是负数:


a[::-1]    # all items in the array, reversed

a[1::-1]   # the first two items, reversed

a[:-3:-1]  # the last two items, reversed

a[-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()对象简化了切片的编程生成。


查看完整回答
反对 回复 2019-05-20
?
缥缈止盈

TA贡献2041条经验 获得超4个赞

列举语法允许的可能性:


>>> seq[:]                # [seq[0],   seq[1],          ..., seq[-1]    ]

>>> seq[low:]             # [seq[low], seq[low+1],      ..., seq[-1]    ]

>>> seq[:high]            # [seq[0],   seq[1],          ..., seq[high-1]]

>>> seq[low:high]         # [seq[low], seq[low+1],      ..., seq[high-1]]

>>> seq[::stride]         # [seq[0],   seq[stride],     ..., seq[-1]    ]

>>> seq[low::stride]      # [seq[low], seq[low+stride], ..., seq[-1]    ]

>>> seq[:high:stride]     # [seq[0],   seq[stride],     ..., seq[high-1]]

>>> seq[low:high:stride]  # [seq[low], seq[low+stride], ..., seq[high-1]]

当然,如果(high-low)%stride != 0,那么终点将会略低于high-1。


如果stride是负数,则排序会因为我们倒计时而改变一点:


>>> seq[::-stride]        # [seq[-1],   seq[-1-stride],   ..., seq[0]    ]

>>> seq[high::-stride]    # [seq[high], seq[high-stride], ..., seq[0]    ]

>>> seq[:low:-stride]     # [seq[-1],   seq[-1-stride],   ..., seq[low+1]]

>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]

扩展切片(带逗号和省略号)主要仅由特殊数据结构(如NumPy)使用; 基本序列不支持它们。


>>> class slicee:

...     def __getitem__(self, item):

...         return repr(item)

...

>>> slicee()[0, 1:2, ::5, ...]

'(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'


查看完整回答
反对 回复 2019-05-20
  • 4 回答
  • 0 关注
  • 772 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信