python切片长度_在Python中从切片对象检索切片的长度

The title explains itself, how to get 2 out of the object

slice(0,2)

The documentation is somewhat confusing, or it is the wrong one

In particular I don't understand what is the meaning of the output of

slice(0,2).indices(0) # (0, 0, 1)

slice(0,2).indices(10 ** 10) # (0, 2, 1)

One possible workaround is to slice a list with the slice object

a = [1,2,3,4,5]

len(a[slice(0,2)]) # 2

But this will fail for an arbitrary large slice.

Thanks, I couldn't find an answer In other posts.

解决方案

There is no complete answer for this. slice doesn't give you a length because the length of the result is always dependent on the size of the sequence being sliced, a short sequence (including an empty sequence) will produce fewer items, and if the slice is unbounded, then the length will grow in tandem with the length of the sequence; a slice might just go "to end of sequence" by having a start or stop of None.

For a quick and easy way to compute the length for a sequence of a known length, you just combine .indices with Py3's range (or xrange in Py2, though xrange has limitations on values that Py3 range does not). slice.indices gives you the concrete start, stop and stride values derived when a slice applies to a sequence of a given length, it's basically the values you'd fill in in a C-style for loop that traverses the same indices as the slice:

for (ssize_t i = start; i < stop; i += stride)

So to calculate the length of a slice when applied to a sequence with 1000 elements, you'd do:

>>> len(range(*slice(0, 2).indices(1000)))

2

>>> len(range(*slice(10, None, 3).indices(1000)))

330

If you're on Python 2, and your values might exceed what xrange can handle (it's limited to bounds and total length equal to what a ssize_t can hold), you can just do the calculation by hand:

def slice_len_for(slc, seqlen):

start, stop, step = slc.indices(seqlen)

return max(0, (stop - start + (step - (1 if step > 0 else -1))) // step)

>>> slice_len_for(slice(10, None, 3), 1000)

330

Update: Unfortunately, slice.indices itself won't accept a len for the sequence beyond what a long can hold, so this doesn't gain you anything over using xrange in Py2. Left in place for those interested, but the workaround doesn't workaround anything unless you also perform the work slice does to convert negative values and None to concrete values based on the sequence length. Sigh.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值