繁体   English   中英

Python列表理解用函数作为输出和条件

[英]Python list comprehension with a function as the output and the conditional

给定一些可以返回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]

你的问题是函数产生的是None ,而不是你迭代的东西。 尝试

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

只需结合您的解决方案

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM