为了帮助我更好地理解 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
您可以使用 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]
请注意我是如何在第一行中使用 (parentheses)
而不是 [brackets]
的。这叫做 generator expression .它允许 rot_points
在第二行中使用点时即时构建,而不是先在内存中构建所有 rot_points
然后然后 遍历它们。如果这是一个问题,它基本上可以节省一些不必要的内存使用量。
我是一名优秀的程序员,十分优秀!