这是一段代码,它为我提供了与期望不同的答案。这行:print list(x)
符合我的期望。我希望这行:print random_array[list(x)]
返回数组中该元素的值,但它返回三个数组。例如,如果list(x)
返回[9, 8, 7]
,则将打印random_array[9, :, :], random_array[8, :, :], random_array[7, :, :]
。有人可以向我解释为什么吗?以及如何获得预期的答案?
import numpy as np
import itertools
random_array = np.random.randint(0, 9, (10, 10, 10))
my_iterator = itertools.product(range(10),range(10),range(10))
for x in my_iterator:
print list(x)
print random_array[list(x)]
最佳答案
您传递的是列表而不是元组:
# What you are doing
random_array[[2, 3, 3]] # semantics: [arr[2], arr[3], arr[3]]
# What you want to be doing
random_array[(2, 3, 3)] # semantics: arr[2][3][3], same as arr[2,3,3]
简而言之:不要使用
list(...)
将元组转换为列表。关于python - 使用itertools索引数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9432355/