Lambdas 中的 if 语句问题 Python3
Issues with if statements within Lambdas Python3
我目前正在编写一些代码来缩放矢量图形,但是我在 Python 中编写错误处理代码时遇到了一些问题,尤其是在 scalePoints 中设置 scaled_points 的行中。该函数采用坐标列表(作为元组)、视口大小和收缩因子,以及 returns 一组按比例缩放的坐标。
我试图通过在 lambda 中使用 if 语句来避免被零除,但在某些测试用例下它似乎不起作用。例如,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)
将 point[0]
and/or point[1]
与 0.0 进行比较不会保护您不被零除,因为它们是分子,而不是分母。
改为检查分母 scale
。
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))
另外,比较浮点数,无论是在什么表达式中,都需要小心。见 link
在你的情况下,添加类似
的内容可能会有所帮助
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 point: (point[0]/scale if point[0] else 0.0, point[1]/scale if point[1] else 0.0)
我目前正在编写一些代码来缩放矢量图形,但是我在 Python 中编写错误处理代码时遇到了一些问题,尤其是在 scalePoints 中设置 scaled_points 的行中。该函数采用坐标列表(作为元组)、视口大小和收缩因子,以及 returns 一组按比例缩放的坐标。
我试图通过在 lambda 中使用 if 语句来避免被零除,但在某些测试用例下它似乎不起作用。例如,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)
将 point[0]
and/or point[1]
与 0.0 进行比较不会保护您不被零除,因为它们是分子,而不是分母。
改为检查分母 scale
。
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))
另外,比较浮点数,无论是在什么表达式中,都需要小心。见 link
在你的情况下,添加类似
的内容可能会有所帮助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 point: (point[0]/scale if point[0] else 0.0, point[1]/scale if point[1] else 0.0)