Python Store Slice Index as Object

守給你的承諾、 提交于 2019-12-11 06:04:07

问题


Say I have a list of lists of lists etc... of some depth:

ExampleNestedObject = numpy.ones(shape = (3,3,3,3,3))

In general I can get an element by writing:

#Let:
#a, b, c, d, e -> are integers

print ExampleNestedObject[a][b][c][d][e]

#numpy also happens to allow:

print ExampleNestedObject[(a,b,c,d,e)]

#python in general allows:

print ExampleNestedObject[a,b,:,d,e]

My question is -> how can I store the index "a,b,:,d,e" as an object?

SomeSliceChoice = a,b,:,d,e

print ExampleNestedObject[SomeSliceChoice]

回答1:


The trick is to think of an index object as a tuple of slice objects.

Example1:

Object[1,2,:] == Object[(1,2,slice(None,None,None))]

Example2:

WantedSliceObject = (1,2,slice(None,None,None), 4,5)
Object[1,2,:,4,5] == Object[WantedSliceObject]

Note the syntax of '''slice:

#slice(start, stop[, step])

#1 ==  slice(1, 2, 1)

WantedSliceObject2 = (
   slice(1, 2, 1),
   slice(2, 2, 1),
   slice(None,None,None), 
   slice(4, 2, 1),
   slice(5, 2, 1)
   )

#WantedSliceObject2 == WantedSliceObject


来源:https://stackoverflow.com/questions/40392885/python-store-slice-index-as-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!