我有以下问题。我有一个参数frc_size。根据fcr_size的大小,必须在if条件中检查更多距离。有没有办法处理这种聪明并缩短所有这些表达方式?例如,对于fcr_size = 3,if条件如下:
minusscore = 2
for coords in full_box:
mindist = float("inf")
for m in range(len(lineSegmentPairs[0])):
newdist = dist(lineSegmentPairs[0][m], lineSegmentPairs[1][m], coords)
if newdist<mindist:
mindist=newdist
if mindist <= radius :
val1 = int(sparse1.get(coords,"0")[0]) - minusscore
sparse1[coords] = [str(val1)]
elif mindist <= (radius +1) :
val1 = int(sparse1.get(coords,"0")[0]) + 3
sparse1[coords] = [str(val1)]
elif mindist <= (radius +2) :
val1 = int(sparse1.get(coords,"0")[0]) + 2
sparse1[coords] = [str(val1)]
elif mindist <= (radius +3) :
val1 = int(sparse1.get(coords,"0")[0]) + 1
sparse1[coords] = [str(val1)]
elif mindist > (radius +3) :
continue
但是如果fcr_size为4,则需要额外的if条件,如:
minusscore = 2
for coords in full_box:
mindist = float("inf")
for m in range(len(lineSegmentPairs[0])):
newdist = dist(lineSegmentPairs[0][m], lineSegmentPairs[1][m], coords)
if newdist<mindist:
mindist=newdist
if mindist <= radius :
val1 = int(sparse1.get(coords,"0")[0]) - minusscore
sparse1[coords] = [str(val1)]
elif mindist <= (radius +1) :
val1 = int(sparse1.get(coords,"0")[0]) + 4
sparse1[coords] = [str(val1)]
elif mindist <= (radius +2) :
val1 = int(sparse1.get(coords,"0")[0]) + 3
sparse1[coords] = [str(val1)]
elif mindist <= (radius +3) :
val1 = int(sparse1.get(coords,"0")[0]) + 2
sparse1[coords] = [str(val1)]
elif mindist <= (radius +4) :
val1 = int(sparse1.get(coords,"0")[0]) + 1
sparse1[coords] = [str(val1)]
elif mindist > (radius +4) :
continue
答案 0 :(得分:2)
也许是这样的?
if mindist <= radius:
val1 = int(sparse1.get(coords,"0")[0]) - minusscore
sparse1[coords] = [str(val1)]
elif mindist > (radius + fcr_size):
continue
else:
for i in range(fcr_size):
if mindist <= radius + i + 1:
val1 = int(sparse1.get(coords,"0")[0]) + (fcr_size - i)
sparse1[coords] = [str(val1)]
break
答案 1 :(得分:1)
似乎if语句中的代码遵循一种模式,可以转换为for循环。每个elif
语句可以是循环的一次迭代,其中包含变量而不是硬编码的数字。它会显着减少代码的大小