Lambdas Python3中if语句的问题
我目前正在编写一些用于缩放矢量图形的代码,但在用Python编写错误处理代码时遇到了一些问题,特别是在scalePoints中设置缩放点的行中。该函数获取坐标列表(作为元组)、视口大小和收缩因子,并返回一组按比例缩放的坐标 我试图通过在lambda中使用if语句来避免被零除,但在某些测试用例下,它似乎不起作用。例如,Lambdas Python3中if语句的问题,python,python-3.x,python-3.7,Python,Python 3.x,Python 3.7,我目前正在编写一些用于缩放矢量图形的代码,但在用Python编写错误处理代码时遇到了一些问题,特别是在scalePoints中设置缩放点的行中。该函数获取坐标列表(作为元组)、视口大小和收缩因子,并返回一组按比例缩放的坐标 我试图通过在lambda中使用if语句来避免被零除,但在某些测试用例下,它似乎不起作用。例如,scalePoints([(0.0,1.0)],300,10)导致被零除,但是scalePoints([(0.0,0.0)],300,10)没有,我不太清楚为什么会这样 def sc
scalePoints([(0.0,1.0)],300,10)
导致被零除,但是scalePoints([(0.0,0.0)],300,10)
没有,我不太清楚为什么会这样
def scalePoints(points, viewport_size, shrink_factor):
min_x = findMinX(points)
max_x = findMaxX(points)
width = max_x - min_x
scale = (width/viewport_size) * shrink_factor
scaled_points = list(map(lambda point: (0.0 if point[0] == 0.0 else (point[0]/scale), 0.0 if point[1] == 0.0 else (point[1]/scale)),points))
return scaled_points
def findMaxX(points):
xs = list(map(lambda point: point[0], points))
return max(xs)
def findMinX(points):
xs = list(map(lambda point: point[0], points))
return min(xs)
将
点[0]
和/或点[1]
与0.0进行比较并不能防止被零除,因为它们是分子,而不是分母
请尝试检查分母,比例
scaled_points = list(map(lambda point: (0.0 if scale == 0.0 else (point[0]/scale), 0.0 if scale == 0.0 else (point[1]/scale)),points))
将
点[0]
和/或点[1]
与0.0进行比较并不能防止被零除,因为它们是分子,而不是分母
请尝试检查分母,比例
scaled_points = list(map(lambda point: (0.0 if scale == 0.0 else (point[0]/scale), 0.0 if scale == 0.0 else (point[1]/scale)),points))
另外,比较浮动,无论是什么表达式,都需要小心。请参阅链接 在您的情况下,添加以下内容可能会有所帮助
scaled_points = list(map(lambda point: (0.0 if math.isclose(point[0], 0.0,rel_tol=1e-5) else (point[0]/scale), 0.0 if math.isclose(point[0], 0.0,rel_tol=1e-5) else (point[1]/scale)),points))
另外,比较浮动,无论是什么表达式,都需要小心。请参阅链接 在您的情况下,添加以下内容可能会有所帮助
scaled_points = list(map(lambda point: (0.0 if math.isclose(point[0], 0.0,rel_tol=1e-5) else (point[0]/scale), 0.0 if math.isclose(point[0], 0.0,rel_tol=1e-5) else (point[1]/scale)),points))
按如下方式更换lambda: lambda点:(点[0]/比例如果点[0]否则0.0,点[1]/比例如果点[1]否则0.0)
按如下方式更换lambda: lambda点:(点[0]/比例如果点[0]否则0.0,点[1]/比例如果点[1]否则0.0)
有时,甚至经常,用一个名字写一个“实”函数要比用一个lambda来拟合它的所有限制要容易得多……用一个简单的for循环来获得缩放点也可能比用lambda来绘制地图更清晰。有时,甚至经常,写一个“实”函数具有名称的函数比尝试在lambda中拟合所有对象及其所有限制要容易得多…获取缩放点的简单for循环也可能比具有lambda的贴图更清晰。