问题描述
我有一个随机长度可变的点的列表,我希望能够独立但同时对这些对象应用变换(在这种情况下为移位)。
list = [Dot(),Dot() ...] # Variable length
我正在使用 3blue1brown 的 https://github.com/3b1b/manim 的 Manim 库。 请注意,其他相关帖子不能解决我的问题,因为它们只能处理固定数量的对象(点)。
解决方法
不要使用 list
,它是一个保留字,使用 VGroup
来包含对象:
list_dots = VGroup(*[Dot() for _ in range(5)]) # 5 dots vgroup
# this is the same as:
# list_dots = VGroup(Dot(),Dot(),Dot())
# See 'list comprehension python' in google
list_dots.arrange(RIGHT)
list_dots.set_color(RED)
list_dots.shift(UP)
,
以reddit post中的以下代码为例,解决了该问题:
import numpy as np
class DotsMoving(Scene):
def construct(self):
dots = [Dot() for i in range(5)]
directions = [np.random.randn(3) for dot in dots]
self.add(*dots) # It isn't absolutely necessary
animations = [ApplyMethod(dot.shift,direction) for dot,direction in zip(dots,directions)]
self.play(*animations) # * -> unpacks the list animations
特别感谢u/Xorlium。