Python List Comprehension: Using an If Expression as a Result of Understanding

Can you filter the list comprehension based on the result of the conversion in comprehension?

For example, suppose you want to split each line in a list and delete lines that are just empty. I could easily do the following:

filter(None, [x.strip() for x in str_list])

But this is repeated over the list twice. Alternatively, you can do the following:

[x.strip() for x in str_list if x.strip()]

But this implementation performs striptwice. I could also use a generator:

for x in str_list:
   x = x.strip()
   if x:
      yield x

, . (1) ; (2) ; (3) ? - , .

: Python 2.7.X , Python 3 , , .

+4
2

filter, , :

filter(None, (x.strip() for x in str_list))

,

[y for y in (x.strip() for x in str_list) if y]

: str_list , . .

, . , , . for.

+2

?

result = (x for x in (y.strip() for y in str_list) if len(x))

() , str_list. () , . .

0

Source: https://habr.com/ru/post/1689600/


All Articles