gpt4 book ai didi

python - 帮我 lambda-nize 这个

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:20 24 4
gpt4 key购买 nike

为了帮助我更好地理解 lambda,我编写了这个旋转和变换四边形的简短片段(希望我的数学计算正确)。现在,我想用一个线性 lambda 替换下面的三个步骤,可能与 map() 结合使用。

我正在使用 vector class但希望这些功能清楚地说明了它们的作用。

self.orientation = vector(1,0)
self.orientation.rotate(90.0)

#the four corners of a quad
points = (vector(-1,-1),vector(1,-1),vector(1,1),vector(-1,1))
print points

#apply rotation to points according to orientation
rot_points = []
for i in points:
rot_points.append(i.rotated(self.orientation.get_angle()))
print rot_points

#transform the point according to world position and scale
real_points = []
for i in rot_points:
real_points.append(self.pos+i*self.scale)
print real_points

return real_points

最佳答案

您可以使用 mapreduce 等,但现在列表理解是在 Python 中做事的首选方式:

rot_points  = (i.rotated(self.orientation.get_angle()) for i in points)
real_points = [self.pos+i*self.scale for i in rot_points]

请注意我是如何在第一行中使用 (parentheses) 而不是 [brackets] 的。这叫做 generator expression .它允许 rot_points 在第二行中使用点时即时构建,而不是先在内存中构建所有 rot_points 然后然后 遍历它们。如果这是一个问题,它基本上可以节省一些不必要的内存使用量。

关于python - 帮我 lambda-nize 这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com