简体   繁体   English

Python:将列表分配给多维数组元素

[英]Python: Assign list to multidimensional array element

I want to do an assignment to a multidimensional array where each element of the array is 3 short integers: 我想对多维数组进行赋值,其中数组的每个元素都是3个短整数:

a = ndarray([3,3,3], dtype='u2,u2,u2')
a[2,2,2] = [1,2,3]

Traceback (most recent call last): File "", line 1, in a[2,2,2] = [1,2,3] TypeError: expected a readable buffer object 追溯(最近一次调用最后一次):文件“”,第1行,在[[2,2,2] = [1,2,3]中TypeError:预期为可读缓冲区对象

I am going to be using a large array and would like to get direct indexing into the array for performance. 我将使用大型数组,并希望直接索引到数组中以提高性能。 What is a good way to do this in python? 在python中执行此操作的好方法是什么?

Thanks for any insight into how to do this? 感谢您对如何执行此操作有任何见解?

The elements of an array of dtype='u2,u2,u2' are a tuple of three shorts, not a list of three shorts. dtype='u2,u2,u2'数组的元素是三个短裤的元组 ,而不是三个短裤的列表 So: 所以:

a[2,2,2] = (1,2,3)

(The parens are of course not necessary, but I used them to make it obvious this is a tuple.) (当然没有必要使用括号,但是我用它们使它很明显这是一个元组。)

You can also pass it an array if you want: 您还可以根据需要将其传递给array

a[2,2,2] = np.array([1,2,3])

Of course the error message here certainly could be better… What it's actually complaining about is something deeper than what you'd expect, and it doesn't help you debug the problem. 当然,这里的错误消息肯定会更好……实际上,它所抱怨的是比您期望的要深的东西,它并不能帮助您调试问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM