Single line for loop over iterator with an “if” filter?

前端 未结 8 595
清歌不尽
清歌不尽 2020-12-13 12:55

Silly question:
I have a simple for loop followed by a simple if statement:

for airport in airports:
    if airport.is_important:

and

相关标签:
8条回答
  • 2020-12-13 13:17

    Using list comprehension (only if airports is a list of objects):

    for airport in [a for a in airports if a.is_important]:
    
    0 讨论(0)
  • 2020-12-13 13:18

    Mabe this, but it's more or less the same verbose...

    import itertools
    
    for airport in itertools.ifilter(lambda x: x.is_important, airports):
        ...
    
    0 讨论(0)
提交回复
热议问题