numpy 允许您使用array[1,2,3] 等语法对多维数组进行索引。它通过覆盖项目 getter 来接受 tuple 而不是整数或可散列对象(如列表和字典)来做到这一点。但是numpy 在处理维度变化的数组时就不是那么优雅了,所以你不会有太多运气直接切换到numpy。
不过,您可以使用类似的技术。您的索引可以是tuple(或任何序列,真的),然后它只是编写支持框架的一个案例。由于构建一个类可能很复杂,我所做的只是实现了一个使用tuple 索引的函数,并且我添加了一个用于测试的枚举函数。
array = [[[0.34774399349216734, -0.49837251730235765, 0.12359046385526962, 0.03052580675850769],
[0.9030134040537152, -0.7537158452634996, 0.2910583603657293, -0.22034711903454673]],
[[-0.9383578579687082, -0.2281750912629248, 0.052722557936115466]]]
def array_enum(array):
"""enumerate multidimensional array returning indextuple, value for
each leaf node value.
"""
for i, item in enumerate(array):
if isinstance(item, list):
for subindex, val in array_enum(item):
yield (i,) + subindex, val
else:
yield (i,), item
def array_get_item(array, indextuple):
"""Use index values in indextuple to return item from
multidimensional array.
"""
for i in indextuple[:-1]:
array = array[i]
return array[indextuple[-1]]
for indextuple, val in array_enum(array):
orig_val = array_get_item(array, indextuple)
print(indextuple, val, orig_val, val == orig_val)
您的示例数组的结果是
(0, 0, 0) 0.34774399349216734 0.34774399349216734 True
(0, 0, 1) -0.49837251730235765 -0.49837251730235765 True
(0, 0, 2) 0.12359046385526962 0.12359046385526962 True
(0, 0, 3) 0.03052580675850769 0.03052580675850769 True
(0, 1, 0) 0.9030134040537152 0.9030134040537152 True
(0, 1, 1) -0.7537158452634996 -0.7537158452634996 True
(0, 1, 2) 0.2910583603657293 0.2910583603657293 True
(0, 1, 3) -0.22034711903454673 -0.22034711903454673 True
(1, 0, 0) -0.9383578579687082 -0.9383578579687082 True
(1, 0, 1) -0.2281750912629248 -0.2281750912629248 True
(1, 0, 2) 0.052722557936115466 0.052722557936115466 True