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

前端 未结 8 636
清歌不尽
清歌不尽 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:14

    I found the usage of the filter & lambda to be the easiest in a single line.

    for filtered_airport in filter(lambda airport: airport.is_important, airports)):
        print(filtered_airport.some_property)
    

    If you wish to return a list from output of this filter object you can do something like this.

    filtered_airport_list = list(filter(lambda airport: airport.is_important, airports)))
    

提交回复
热议问题