【问题标题】:Function in Python list comprehension, don't eval twicePython 列表推导中的函数,不要求值两次
【发布时间】:2023-01-15 14:55:52
【问题描述】:

我正在通过一个转换函数从一个输入列表中编写一个 Python 列表。我只想在输出列表中包含那些结果不是 None 的项目。这有效:

def transform(n):
    # expensive irl, so don't execute twice
    return None if n == 2 else n**2


a = [1, 2, 3]

lst = []
for n in a:
    t = transform(n)
    if t is not None:
        lst.append(t)

print(lst)
[1, 9]

我有一种预感,这可以通过理解来简化。然而,直接的解决方案

def transform(n):
    return None if n == 2 else n**2


a = [1, 2, 3]
lst = [transform(n) for n in a if transform(n) is not None]

print(lst)

不好,因为 transform() 对每个条目应用了两次。有办法解决这个问题吗?

【问题讨论】:

  • 如果您有 Python 3.8 或更高版本,则可以使用 walrus operator 来保存函数调用的结果。
  • 另一种选择是使用@functools.lru_cache

标签: python list-comprehension


【解决方案1】:

对 python >=3.8 使用 := 运算符。

lst = [t for n in a if (t:= transform(n)) is not None]

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多