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

问题描述 投票:0回答:1

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

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)])
python numpy tensor
1个回答
0
投票

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

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

因此,在你的例子中,NS不能用作1, 0, 0(这是一个tuple)的替代品,但明确地确保NS是一个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

NS = [1, 0, 0]
print(qn[tuple(NS)])

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

© www.soinside.com 2019 - 2024. All rights reserved.