简体   繁体   English

从切片对象解析切片信息?

[英]Parsing slice information from a slice object?

I'm trying to get the information from a slice. 我正在尝试从切片中获取信息。 Here's the start of my function. 这是我功能的开始。 (I have tried "elif isinstance(key, slice):" for the fourth line and can't get that to work) (我在第四行尝试了“ elif isinstance(key,slice):”,但无法正常工作)

    def __getitem__(self, key):
    if isinstance(key,(int, long)):
        #do stuff if an int
    elif #item is slice
        #do stuff if a slice

If I make a function call of obj[4:6] to call this function and I print the "key" variable in the function, it prints "slice(4,6, None)" How do I parse the 4 and 6 values? 如果我对obj [4:6]进行函数调用以调用此函数,并且在函数中打印了“ key”变量,则它将打印“ slice(4,6,None)”如何解析4和6值? What I"m trying to do is be able to use the data from the list inside the function. 我想做的是能够使用函数内列表中的数据。

>>> slice(4,5).start
4
>>> slice(4,5).stop
5
>>> slice(4,5).step  #None

One particularly useful method of the slice object is the indices method: 切片对象的一种特别有用的方法是indices方法:

>>> slice(4,5).indices(12)
(4, 5, 1)

You might use it like this: 您可以这样使用它:

 for i in range(*my_slice.indices(len(self))):
     print self[i]

Note that this really shines with negative indices or steps: 请注意,这确实带有负索引或步骤:

>>> slice(4,-5).indices(12)
(4, 7, 1)
>>> print range(*slice(None,None,-1).indices(12))
[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

If you want the info from the slice object, access its attributes start , stop , and step . 如果要从slice对象获取信息,请访问其属性startstopstep These attributes are documented here . 这些属性在此处记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM