# Define the data (this could be measured at runtime)
data_shape = (3, 5, 7, 11, 13)
print('data_shape = {}'.format(data_shape))
# Pick which index to slice from which dimension (could also be decided at runtime)
slice_dim = len(data_shape)/2
slice_index = data_shape[slice_dim]/2
print('slice_dim = {} (data_shape[{}] = {}), slice_index = {}'.format(slice_dim, slice_dim, data_shape[slice_dim], slice_index))
# Make a data set for testing
data = arange(product(data_shape)).reshape(*data_shape)
# Slice the data
s = [slice_index if a == slice_dim else slice(None) for a in range(len(data_shape))]
d = data[s]
print('shape(data[s]) = {}, s = {}'.format(shape(d), s))
# Store the variables that represent the slice in a list/tuple
# Make a slice with the unzipped tuple using the slice() command
# Use the slice on your array
示例:
>>> from numpy import *
>>> a = (1, 2, 3)
>>> b = arange(27).reshape(3, 3, 3)
>>> s = slice(*a)
>>> b[s]
array([[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]])
如果一切都是在运行时决定的,您可以:
虽然这比
ndarray.take()
长,但如果slice_index = None
,它将工作,就像数组的维度太少,以至于您实际上不想对其进行切片(但您不知道您不想提前对其进行切片)一样。这样做的一个选项是以编程方式构造切片:
另一种方法是使用
numpy.take()
或ndarray.take()
:您可以使用slice函数,并在运行时使用适当的变量列表调用它,如下所示:
示例:
这与:
最后,在通常的表示法中不指定2
:
之间的任何内容的等价物是将None
放在您创建的元组中的那些位置。相关问题 更多 >
编程相关推荐