将值附加到对象内的数组(在对象上循环)

bno*_*ets 0 python vectorization

这是问题的简洁版本。由于我做了很多改变,所以我提出了一个新问题

我试图从较长的数组中获取某些值solution,并将它们放入对象内的较小数组中。该代码应采用solution数组的前半部分放入x_hist内部m1,以及solution数组的后半部分放入x_hist内部m2。取而代之的是,它似乎将所有solution数组x_hist都放入两个对象中。有人知道为什么会这样吗?我是否不小心将代码矢量化了?

class Mass:
    x_hist = []

m1 = Mass()
m2 = Mass()
ms = [m1,m2]

solution = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0]

for i in range(len(ms)):
    for k in range(int(len(sol)/len(ms))):
        ms[i].x_hist.append(solution[k+8*i])

print(m1.x_hist)
print(m2.x_hist)
Run Code Online (Sandbox Code Playgroud)

输出为:

[1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)

我正在尝试获得以下输出:

[1, 2, 3, 4, 5, 6, 7, 8]
[0, 0, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)

Aka*_*ari 5

x_hist属性是静态类属性

variables Declared inside classes are static variables different from the context of instance which means,

>>> s = M()
>>> s
<__main__.M object at 0x7f9ffb4a6358>
>>> s.i
3
>>> M.i
3
>>> s.i = 4
>>> M.i
3
>>> s.i
4



class Mass:
    #x_hist = [] shared by all classes its static
    def __init__(self):
        self.x_hist = []

m1 = Mass()
m2 = Mass()
ms = [m1,m2]

solution = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0]

for i in range(len(ms)):
    for k in range(int(len(sol)/len(ms))):
        ms[i].x_hist.append(solution[k+8*i])

print(m1.x_hist)
print(m2.x_hist)
Run Code Online (Sandbox Code Playgroud)

For static Method and ClassMethod check Here

For Nice Tutorial for Classes Refer Here