简体   繁体   English

如何在python中访问切片对象的元素

[英]How do I access the elements of a slice object in python

I'm using scipy.ndimage.label and scipy.ndimage.find_objects to find things in an image. 我正在使用scipy.ndimage.label和scipy.ndimage.find_objects来查找图像中的内容。 It returns an array of slices. 它返回一个切片数组。 I am trying to get the coordinates of the object out of the slice but can't seem to find a way to get inside the slice object. 我试图从切片中获取对象的坐标,但似乎无法找到进入切片对象的方法。 Here is a simple example: 这是一个简单的例子:

a = 1
b = 2
c = 13
d = 47
j = slice(a,b,None)
k = slice(c,d,None)
x = (j, k)

print(x)
print(x[0])
print(x[0].indices(2))
print(x[1].indices(2))

Output is: 输出是:

(slice(1, 2, None), slice(13, 47, None))
slice(1, 2, None)
(1, 2, 1)
(2, 2, 1)

Basically I am looking for the ability to get the values for a, b, c, and d if I'm only given the slice tuple x. 基本上我正在寻找获得a,b,c和d的值的能力,如果我只给出切片元组x。 I thought indices would get me on the way but I'm not understanding it's behavior. 我认为指数会让我在路上,但我不理解它的行为。

Are you looking for the start , stop and step properties? 您在寻找startstopstep属性吗?

>>> s = slice(1, 2, 3)
>>> s.start
1
>>> s.stop
2
>>> s.step
3

slice.indices computes the start/stop/step for the indices that would be accessed for an iterable with the input length. slice.indices计算将为具有输入长度的iterable访问的索引的开始/停止/步骤。 So, 所以,

>>> s = slice(-1, None, None)
>>> s.indices(30)
(29, 30, 1)

Which means that you would take item 29 from the iterable. 这意味着您将从迭代中获取项目29。 It is able to be conveniently combined with xrange (or range ): 它可以方便地与xrange (或range )组合:

for item in range(*some_slice.indices(len(sequence))):
    print(sequence[item])

As a concrete example: 作为一个具体的例子:

>>> a = range(30)
>>> for i in a[-2:]:
...   print(i)
... 
28
29
>>> s = slice(-2, None, None)
>>> for ix in range(*s.indices(len(a))):
...   print(a[ix])
... 
28
29

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

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