在下面的函数中缩进/格式化行的好方法是什么?或者我根本不应该尝试把它写成一行吗?
def rects_bound(rects):
""" Returns a rectangle that bounds all given rectangles
"""
return reduce(lambda (ax,ay,aw,ah), (bx,by,bw,bh): (min(ax,bx),
min(ay,by),
max(ax+aw, bx+bw),
max(ay+ah, by+bh)), rects)
或者也许
def rects_bound(rects):
""" Returns a rectangle that bounds all given rectangles
"""
return reduce(lambda (ax,ay,aw,ah),
(bx,by,bw,bh): (min(ax,bx), min(ay,by),
max(ax+aw, bx+bw), max(ay+ah, by+bh)),
rects)
我通常只是在这些情况下“发挥创意”,我知道可能没有“正确”的方法,我只是对您的意见和习惯感兴趣。
最佳答案
首先,尽可能避免排长队。这个特殊的例子可以写成更具可读性的
def rects_bound(rects):
x0 = min(x for x, y, w, h in rects)
y0 = min(y for x, y, w, h in rects)
x1 = max(x + w for x, y, w, h in rects)
y1 = max(y + h for x, y, w, h in rects)
return x0, y0, x1, y1
如果你喜欢避免变量,你也可以使用
def rects_bound(rects):
return (min(x for x, y, w, h in rects),
min(y for x, y, w, h in rects),
max(x + w for x, y, w, h in rects),
max(y + h for x, y, w, h in rects))
我仍然觉得它比您的原始代码更具可读性。
(请注意,我假设 rects
允许多次迭代。)
关于python - 格式化长 python 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8762409/