[英]How to make different element for each row in numpy array variable?
I try to make the output y that have different element per row.我尝试使输出 y 每行具有不同的元素。 But when I print y again, the output show that y have the same element for each row.
但是当我再次打印 y 时,输出显示 y 对于每一行都有相同的元素。 What is the correct way to create y with different element for each row?
为每行创建具有不同元素的 y 的正确方法是什么?
import numpy as np
class temp:
x = []
y = np.tile(temp, (3, 1))
y
for i in range(3):
y[i, 0].x = np.random.rand(1,5)
print(y[i,0].x)
for i in range(3):
print(y[i,0].x)
You shouldn't be trying to make arrays of custom class objects.您不应该尝试制作自定义类对象的数组。 This will not replicate the MATLAB
struc
(in your next question).这不会复制 MATLAB
struc
(在您的下一个问题中)。
But if you do define a class, use a more conventional format, such as:但如果你确实定义了一个类,请使用更传统的格式,例如:
In [39]: class Temp:
...: def __init__(self, x):
...: self.x = x
...: def __repr__(self):
...: return f'Temp ({self.x})'
...:
In [40]: a = Temp([1,2,3]); b = Temp([4,5])
In [41]: a
Out[41]: Temp ([1, 2, 3])
In [42]: a.x
Out[42]: [1, 2, 3]
In [43]: b
Out[43]: Temp ([4, 5])
a
and b
are instances of the class, each with their own x
attribute. a
和b
是类的实例,每个都有自己的x
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.