【问题标题】:Python list comprehension with a function as the output and the conditional以函数作为输出和条件的 Python 列表推导
【发布时间】:2017-10-02 23:08:27
【问题描述】:

给定一些可以返回 None 或其他值的函数和一个值列表:

def fn(x):
    if x == 4:
        return None
    else return x

lst = [1, 2, 3, 4, 5, 6, 7]

我想要一个不返回 None 的 fn() 输出列表

我有一些看起来像这样的代码:

output = []
for i in lst:
    result = fn(i)
    if result:
        output.append(result)

我可以将其表达为这样的列表理解:

output = [fn(i) for i in lst if fn(i)]

但它运行fn(i) 任何不返回None 两次如果fn 是一个昂贵的功能是不可取的。

有没有什么方法可以在不运行两次函数的情况下获得很好的 Pythonic 理解?

一个可能的解决方案:

output = [fn(i) for i in lst]
output = [o for o in f if o]

【问题讨论】:

  • 你知道 Pythonic 是什么吗?你的 for 循环。

标签: python list list-comprehension


【解决方案1】:

只需结合您的解决方案:

[x for x in [fn(i) for i in lst] if x is not None]

缺点是fn 生成的原始列表中的任何Nones 也将被删除。

【讨论】:

  • 与None的比较应改为x is not None
【解决方案2】:

您的问题是 None 是由函数产生的,而不是您正在迭代的东西。试试

 output = [fi for fi in map(fn, lst) if fi is not None]

【讨论】:

  • 这基本上是我正在寻找的答案,一种迭代函数结果的方法。谢谢!
猜你喜欢
  • 2017-12-23
  • 2020-02-22
  • 2021-04-12
  • 1970-01-01
  • 2019-04-15
  • 2020-04-07
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多