如何将 lambda 函数分解成它自己的函数? (Lambda 目前是 125+ 个字符)

How to break up lambda function in to its own function? (Lambda is currently 125+ characters)

我有一个 lambda 函数,我想添加它并使其更健壮。然而,我也想遵循 PEP 8 并将我的行保持在 79 个字符以内,正确的缩进等。但是我在思考如何拆分行时遇到了麻烦。

当前行是:

styled_df = df.style.apply(lambda x: ["background: rgba(255,0,0,.3)" if('BBC' in x['newsSource'] or 'Wall' in x['newsSource']) and idx==0 else "" for idx, v in enumerate(x)], axis = 1)

到目前为止,我可以做到这一点:

styled_df = df.style.apply(
    lambda x: ["background: rgba(255,0,0,.3)" 
        if('BBC' in x['newsSource'] or 'Wall' in x['newsSource']) and
        idx == 0 else ""
        for idx, v in enumerate(x)], axis=1)

但第三行 (if('BBC' in ...) 与 PEP 8 (E128) 冲突。另外,不可否认,这不是我分解代码时最清晰的代码。

此外,我正计划为此添加更多条件,并且想知道这样做的最佳方式是什么。只是继续添加,并尽我所能打破线路?或者是否有针对此类问题的'best practice'?

编辑:如我所想,但忘了提及,我可能可以将此 lambda 更改为一个函数,但我正在苦苦思索如何做。我是 lambda 的新手,完全是从另一个问题中得到的...所以是的,我同意 Lambda 是根本问题。

作为一般规则,我认为最好依靠自动化工具来重新格式化您的代码,而不是像自己使用计算机一样尝试弄清楚如何应用所有这些规则。

我知道的三个主要选择是:

  • black:语法层面的重新格式化;除了最大行长度外,根本没有配置。
  • yapf:语法层面的重新格式化;高度可配置。
  • autopep8(以及 pep8ify 等前辈):仅在表面级别重新格式化;不会更改任何已经符合 PEP 8 的内容。如果您想要尽可能少的更改(例如,因为您正在重新格式化长期存在的代码并且不希望源代码管理中有大量更改列表),这很有用。

以下是 black 对您的代码所做的:

styled_df = df.style.apply(
    lambda x: [
        "background: rgba(255,0,0,.3)"
        if ("BBC" in x["newsSource"] or "Wall" in x["newsSource"]) and idx == 0
        else ""
        for idx, v in enumerate(x)
    ],
    axis=1,
)

这会占用大量的垂直空白。但是您不能配置 black 来区别对待它。那么,你能做什么?

每当 black 坚持将我的代码重新格式化为我不喜欢的东西时,这意味着我必须将我的代码重新组织为更易于格式化的代码。

显然要做的是将那个巨人 lambda 变成一个 def,或者甚至两个:

def highlight(x):
    return "BBC" in x["newsSource"] or "Wall" in x["newsSource"]

def style(x):
    return [
        "background: rgba(255,0,0,.3)" if highlight(x) and idx==0 else ""
        for idx, v in enumerate(x)
    ]

styled_df = df.style.apply(style, axis=1)

完成后……您甚至没有使用 v;您所做的只是为第一个 (and idx == 0) 设置样式,并且前提是新闻来源包括 BBC 或 Wall。

因此,对于 BBC 和 Wall 事物,您要返回一个 background 加上 len(x)-1 个空字符串;对于其他事情,您只是返回 len(x) 空字符串。

假设这是你想要的逻辑,让我们明确一点:

def style(x):
    if "BBC" in x["newsSource"] or "Wall" in x["newsSource"]:
        first = "background: rgba(255,0,0,.3)"
        return [first] + [""]*(len(x)-1)
    return [""]*len(x)

styled_df = df.style.apply(style, axis=1)

您可能更喜欢 ["" for _ in range(x)] 而不是 [""]*len(x);我不确定这里哪个更具可读性。


I likely could change this lambda in to a function, but am struggling with how. I'm new to lambdas and got this one from another problem altogether...So yes, agreed the Lambda is the root issue.

A lambda 一个函数,就像def一样。唯一的区别是:

  • def是语句,不能放在表达式中间。
  • lambda 是一个表达式,因此您不能在其中包含任何语句。
  • def 为函数命名。

除此之外,他们编译的函数完全一样。例如:

func = lambda x: expr(x)

def func(x): return expr(x)

… 定义了两个具有相同字节码的函数,几乎所有其他的都相同,除了 func.__name__ 对于 def'func' 而对于 '<lambda>' lambda.

更重要的是,如果你想在函数中加入循环或测试,使用 lambda 你必须将它扭曲成一个推导式或一个 if 表达式;使用 def,如果合适,您可以这样做,如果不合适,则使用复合语句。

但是,另一方面,如果函数没有好的名称,并且除了用作回调函数之外真的不值得考虑,lambda 更好。例如,如果您定义一个函数 return x - 3 并且只会被使用一次,那么 def 就很愚蠢。

要事第一:您的代码在做什么?

大家仔细阅读:

lambda x: ["background: rgba(255,0,0,.3)" 
        if('BBC' in x['newsSource'] or 'Wall' in x['newsSource']) and
        idx == 0 else ""
        for idx, v in enumerate(x)]

您只对 x 的第一个元素感兴趣,因为 idx == 0。请记住,索引仅在第一次迭代中为零。因此,如果 x 有一个 1,000,000 个元素,您将评估 999,999 个无用的 if 条件。

据我了解,你对算法的解释是:

Create a list of the same length of x in which every element is an empty string. If BBC or 'Wall' is present in x['newsSource'] make the first element of this new list be the string background: rgba(255,0,0,.3). Return this new list.

这很容易编码:

def mysterious_function(x):
    new_list = [''] * len(x)

    if 'BBC' in x['newsSource'] or 'Wall' in x['newsSource']:
        new_list[0] = 'background: rgba(255,0,0,.3)'

    return new_list

您现在可以在当前代码中使用神秘函数:

styled_df = df.style.apply(mysterious_function, axis=1)

这样不是更好吗?

(请给函数一个更好的名字)