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

后端 未结 4 1454
余生分开走
余生分开走 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条回答
  •  梦毁少年i
    2021-02-12 04:14

    There is no where statement but you can "emulate" it using for:

    a=[0]
    def f(x):
        a[0] += 1
        return 2*x
    
    print [ (x, y) for x in range(5) for y in [f(x)] if y != 2 ]
    print "The function was executed %s times" % a[0]
    

    Execution:

    $ python 2.py 
    [(0, 0), (2, 4), (3, 6), (4, 8)]
    The function was executed 5 times
    

    As you can see, the functions is executed 5 times, not 10 or 9.

    This for construction:

    for y in [f(x)]
    

    imitate where clause.

提交回复
热议问题