Mention list for loop + triple operation for loop?

I think I understand the concepts in the lists and the triple operation, and I understand that I can combine the two, as shown here . My question involves combining two expressions in one list comprehension.

For example, if I have the following list:

lst = ['word','word','multiple words','word']

and I want to change this list on one line, is there any way to do this? I tried what I considered the most obvious construction:

lst[:] = [word for word in word.split() if ' ' in word else word for word in lst]

This causes a syntax error. Is there a way to do this on a single line?

+4
source share
2 answers

* , str.split() , :

lst[:] = [word for words in lst for word in words.split()]

:

>>> lst = ['word','word','multiple words','word']
>>> [word for words in lst for word in words.split()]
['word', 'word', 'multiple', 'words', 'word']

, ; , - expression old_expression :

list_display        ::=  "[" [expression_list | list_comprehension] "]"
list_comprehension  ::=  expression list_for
list_for            ::=  "for" target_list "in" old_expression_list [list_iter]
old_expression_list ::=  old_expression [("," old_expression)+ [","]]
old_expression      ::=  or_test | old_lambda_expr
list_iter           ::=  list_for | list_if
list_if             ::=  "if" old_expression [list_iter]

, , , ( ), if ( for).

* ; a , SQL BETWEEN.

+3

, . , :

[a if c else b for item in list]

. .

, , - :

[subword for word in list for subword in word.split()]
+3

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


All Articles