我正在致力于从 IDL 到 python 的代码转换,但遇到了障碍。我得到的一些代码需要转换为 python。在 IDL 版本中,数组元素是通过 int 值而不是 3D 索引来访问的。使用相同的技术,python 会报错。有什么想法如何解决这个问题吗?
以下是用于说明目的的 IDL 代码片段:
x = reform(indgen(100), 2, 5, 10)
help, x ;this results in Array[2,5,10]
x[-76] ; results in value 24
这是一段用于说明目的的 Python 代码片段
import numpy as np
x=np.arange(100).reshape(2,5,10)
x.shape #this results in (2,5,10)
x[-76]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index -76 is out of bounds for axis 0 with size 2
NumPy 数组(或 Python 中使用整数索引的任何内容)不仅仅支持扁平类型的索引。其一,它假设我们知道维度在内存中的保存顺序,这可能是有风险的。
但是,NumPy 确实包含一些函数和方法来帮助解决此问题:
import numpy as np
x = np.arange(100).reshape(2, 5, 10)
# to just get the value at that IDL index
print(x.flat[-76])
def idl_idx(xs: np.ndarray, idx: int):
# unravel_index doesn't support negative indices, so convert them
if idx < 0:
idx = xs.size + idx
return np.unravel_index(idx, xs.shape)
# to get the index as a tuple
print(idl_idx(x, -76))
# to just get that value normally
print(x[0, 2, 4])
输出:
24
(0, 2, 4)
24
无法更改
np.ndarray
类型本身来支持此行为,尽管您可以对其进行子类化并添加此行为。但这会存在仅适用于该类型数组的限制,而某些函数(在 NumPy 和其他地方)可能会返回 np.ndarray
类型的新数组,而这些数组将不再像那样工作 - 这可能是您想要避免的事情。