Python list comprehension - want to avoid repeated evaluation

前端 未结 12 2266
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 05:23

I have a list comprehension which approximates to:

[f(x) for x in l if f(x)]

Where l is a list and f(x) is an expensive function which retu

12条回答
  •  轮回少年
    2020-11-27 05:56

    How about defining:

    def truths(L):
        """Return the elements of L that test true"""
        return [x for x in L if x]
    

    So that, for example

    > [wife.children for wife in henry8.wives]
    [[Mary1], [Elizabeth1], [Edward6], [], [], []]
    
    > truths(wife.children for wife in henry8.wives) 
    [[Mary1], [Elizabeth1], [Edward6]]
    

提交回复
热议问题