在函数中使用numpy数组中的数据

2024-04-19 10:36:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做一个简单的太阳系模拟作为实践,但我遇到了一个小问题。你知道吗

我想将简单的行星数据存储在numpy数组中,然后使用该数组中的数据绘制行星。但是,我似乎无法让我的自定义函数正确使用数据。你知道吗

例如,这就是存储数据的方式。你知道吗

# shape as type, size, orbitradius, startx, starty
solsystem = np.array([
                     ['sun', 2, 0, (screenx // 2), (screeny // 2)],
                     ['planet', 1, 200, 200, 200]
                     ])

我试图使用其中的数据的函数。你知道吗

class makebody():
    def new(btype, size, orbitradius, x, y):
        nbody = body()
        nbody.type = btype
        nbody.size = size
        nbody.orbitradius = orbitradius
        nbody.x = x
        nbody.y = y
        nbody.color = (0, 0, 255) #blue

        if (btype == 'sun'):
            nbody.color = (255, 255, 0)  #yellow

        return nbody

我试过了

bvec = np.vectorize(makebody.new)
    body = bvec(solsystem)

以及

for t, size, orbitradius, x, y in np.ndindex(solsystem.shape):
        body = makebody.new(t, size, orbitradius, x, y)

但这些都没有达到预期的效果,也没有起到任何作用。我该怎么做呢,或者说numpy不是这份工作的合适工具?你知道吗


Tags: 数据函数numpynewsizenpbody数组
1条回答
网友
1楼 · 发布于 2024-04-19 10:36:05

我会用字典或者像这个例子中的元组列表。简单有效。然后你可以将你的列表输入到一个类中,生成你的太阳系,然后你就可以很容易地访问你的行星和属性。符号:


class Body:

    def __init__(self, data):
        # data represents one element of solsystem
        self.btype, self.size, self.orbitradius, self.x, self.y, self.color = data

    def __str__(self):
        return f'Name:\t{self.btype}\nSize:\t{self.size}\n' \
               f'Orbit Radius:\t{self.orbitradius}\nPosition:\t{self.x}, {self.y}\nColor:\t{self.color}'


class SolarSystem:

    def __init__(self, solsystem):
        self.bodies = dict()
        for data in solsystem:
            b = Body(data)
            self.bodies[b.btype] = b


if __name__ == '__main__':
    screenx = 600
    screeny = 600

    solsystem = [('sun', 2, 0, (screenx // 2), (screeny // 2), (255, 255, 0)),
                 ('earth', 1, 200, 200, 200, (0, 0, 255)),
                 ('mars', 1, 200, 200, 200, (255, 0, 0))]

    ss = SolarSystem(solsystem)

    print(ss.bodies['sun'])

    # Access attributes with e.g. ss.bodies['sun'].size for the size, etc...

最后的print语句将返回str方法的内容:

Name:   sun
Size:   2
Orbit Radius:   0
Position:   300, 300
Color:  (255, 255, 0)

你知道吗不锈钢阀体只是一本字典,上面有你所有的行星。你知道吗

相关问题 更多 >