提交列表作为 numpy 多维数组的坐标
Commit List as Coordinates for numpy multi-dimensional array
我想提交一个列表作为我的多维 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)])
如果我理解正确(即您想以编程方式从 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。
我想提交一个列表作为我的多维 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)])
如果我理解正确(即您想以编程方式从 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。