提交列表作为numpy多维数组的坐标

时间:2018-09-17 08:22:36

标签: python numpy tensor

我想提交一个列表作为多维numpy数组的一组坐标,而不必分别输入每个坐标。我知道元组是可能的。为什么不选择列表?

import numpy as np

qn=np.random.choice(list(range(100)), 64).reshape(4, 4, 4)

NS=[1,0,0]

print(qn[1,0,0])
#7
print(qn[NS])
#7   #Would be what I've been looking for

#I also tried
print(qn[iter(NS)])

1 个答案:

答案 0 :(得分:0)

如果我正确理解(例如,您希望以编程方式从qn获得单个元素),那么您要做的就是使用tuple而不是list。 请注意,切片和列表描述虽然使用相同的方括号符号[],但执行的操作却大不相同:

  • item[1]访问对象的一部分(取决于实际对象)。
  • [1, 2]生成一个列表,其中包含指定的元素。

因此,在您的示例中,NS不能用作1, 0, 0(它是tuple)的替代,但是必须明确确保NS是{ {1}}(最终具有与以前相同的内容)将达到目的。

tuple

如果import numpy as np np.random.seed(0) # FYI, no need to "cast" `range()` to `list` qn = np.random.choice(range(100), 64).reshape(4, 4, 4) NS = 1, 0, 0 # equivalent to: `NS = (1, 0, 0)` # equivalent to: `NS = tuple(1, 0, 0)` # equivalent to: `NS = tuple([1, 0, 0])` (this is doing a bit more, but the result is equivalent) # this is different from: `NS = [1, 0, 0]` print(qn[NS]) # 39 是通过其他方式生成的NS,那么您要做的就是事先转换为list

tuple

这是NumPy的sophisticated indexing system的一部分。

相关问题