[英]Formatting long python lines
在下面的函數中縮進/格式化行的漂亮方法是什么? 還是我根本不應該嘗試將它寫成一個襯板?
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
允許多次迭代。)
我認為這取決於程序員和情況,但是我通常不喜歡僅僅為了縮短行而分配變量。
看一下您的兩個示例,我將繼續第二個示例,或者這個示例:
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
)
如果您擔心行長,請不要使用lambda
。 請改用常規的命名函數。
def rects_bound(rects):
""" Returns a rectangle that bounds all given rectangles
"""
def bounding_rect_reducer((ax, ay, aw, ah), (bx, by, bw, bh)):
return (min(ax,bx),
min(ay,by),
max(ax+aw, bx+bw),
max(ay+ah, by+bh))
return reduce(bounding_rect_reducer, rects)
您的lambda函數錯誤。 對其進行修復將使其更長,並涉及冗余計算。 使用def代替:
def rects_bound(rects):
""" Returns a rectangle that bounds all given rectangles
"""
def bound_2_rects((ax, ay, aw, ah), (bx, by, bw, bh)):
x = min(ax, bx)
y = min(ay, by)
return x, y, max(ax+aw, bx+bw) - x, max(ay+ah, by+bh) - y
return reduce(bound_2_rects, rects)
我建議以下內容:
def rects_bound(rects):
""" Returns a rectangle that bounds all given rectangles
"""
return reduce(lambda (X,Y,W,H), (x,y,w,h): (min(X,x), min(Y,y),
max(X+W, x+w),
max(Y+H, y+h)), rects)
將每個參數減少為一個字符確實可以節省空間,這有助於使外觀更整潔。 另一個選擇是在單獨的行上定義lambda函數(甚至可以使用def
),以使參數起初不會走得太遠。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.