帮帮我lambda-nize这个

Miz*_*zor 3 python lambda

为了帮助我更好地理解lambda,我编写了这个简短的片段,它可以旋转并转换四边形(我希望我的数学正确).现在,我想用一个衬里lambdas替换下面的三个步骤,可能与map()一起使用.

我使用矢量类,但希望功能很明确,他们做了什么.

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
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 8

您可以使用map,reduce等等,但现在列表推导是在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]
Run Code Online (Sandbox Code Playgroud)

请注意我(parentheses)是如何使用而不是[brackets]在第一行中使用的.这被称为生成器表达式.它允许rot_points在第二行中使用点时动态构造,而不是先构造所有rot_points内存然后迭代它们.它可以节省一些不必要的内存使用,基本上,如果这是一个问题.