python - 格式化长 python 行

标签 python code-formatting

在下面的函数中缩进/格式化行的好方法是什么?或者我根本不应该尝试把它写成一行吗?

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/

相关文章:

python - 如何将列表转换为层次结构字典

c# - 如何在 Delphi 和 C# 中格式化复合语句?

Python 字典排序列表,部分标签可能缺失

python - 如果两个 Tree 具有相同的值节点,则使用 set 进行计数

python - 对数似然成本函数 : mean or sum?

scala - Intellij Scala 类定义格式

visual-studio-2008 - 有没有办法让 Visual Studio 2008 停止格式化我的 AutoProperties?

xml - 是否可以使用 XSLT 对 XML 文档进行颜色编码和格式化?

python - 在 python selenium 中从 HTML 表中提取链接文本