Is it possible to add a where clause with list comprehension?

后端 未结 4 1444
余生分开走
余生分开走 2021-02-12 03:42

Consider the following list comprehension

[ (x,f(x)) for x in iterable if f(x) ]

This filters the iterable based a condition f and

4条回答
  •  粉色の甜心
    2021-02-12 04:26

    Nothing says you must use comprehensions. In fact most style guides I've seen request that you limit them to simple constructs, anyway.

    You could use a generator expression, instead.

    def fun(iterable):
        for x in iterable:
            y = f(x)
            if y:
                yield x, y
    
    
    print list(fun(iterable))
    

提交回复
热议问题