[英]How to access an element of a multidimensional array via a list of indices
I would like to access a specific element of a multidimensional array (ie a tensor) via a defined list of indices. 我想通过定义的索引列表访问多维数组的特定元素(即张量)。 Let's say I have an array "P" in 4 dimension, and a list of indices "ind" defined as 假设我有一个4维数组“ P”,并且索引“ ind”的列表定义为
ind = [0,4,1,3]
which characterized one of its element. 这是其元素之一。 I would like to assign "something" to the element P[0,4,1,3]. 我想为元素P [0,4,1,3]分配“内容”。 However, when I do 但是,当我这样做
P[ind] = "something"
Python understands P[[0,4,1,3]] instead of P[0,4,1,3]. Python理解P [[0,4,1,3]]而不是P [0,4,1,3]。
So, how could I access the element P[0,4,1,3] via "ind" ? 那么,如何通过“ ind”访问元素P [0,4,1,3]?
Thank you very much for your help. 非常感谢您的帮助。
Updated answer : 更新的答案 :
To set a value in an N-dimensional list by a given list of indices the following setter function can be used: 要通过给定的索引列表在N维列表中设置值,可以使用以下setter函数:
def set_val(ndim, ind, val):
arr = ndim
for i in ind[:-1]:
arr = arr[i]
arr[ind[-1]] = val
# usage:
P = [[[42]]]
set_val(P, [0, 0, 0,], 9001)
Original answer : 原始答案 :
To set elements corresponding to given indices of a plain Python list you need to run a loop, something like this: 要设置与普通Python列表的给定索引相对应的元素,您需要运行循环,如下所示:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
ind = [0, 4, 1, 3]
val = 42
for i in ind:
arr[i] = val
Plain Python does not provide vector operations on lists. Plain Python不提供列表上的向量操作。 You might be confusing Python with Pandas. 您可能将Python与Pandas混淆了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.