循环的列表理解+循环的三元运算? [英] List Comprehension For Loop + Ternary Operation For Loop?

查看:55
本文介绍了循环的列表理解+循环的三元运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我了解列表理解和三元运算,并且我可以将两者结合在一起,

I think I understand list comprehensions and ternary operation, and I understand that I can combine the two, as seen here. My question involves combining the two expressions within one list comprehension.

例如,如果我有以下列表:

For instance, if I have the following list:

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

并且我想在一行中修改该列表,有没有办法做到这一点?我尝试了我认为是最明显的构造:

and I want to modify that list in one line, is there a way of doing so? I tried what I thought was the most obvious construction:

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

这将引发语法错误.有一种方法可以做到这一点吗?

That throws a syntax error. Is there a way of doing this in one line?

推荐答案

您在这里不需要任何条件表达式 * ,因为str.split()始终返回列表,即使只包含一个单词:

You don't need any conditional expression* here, as str.split() always returns a list, even if only containing one word:

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']

在语法中可以使用简单表达式的任何地方都可以使用条件表达式;这表示在列表显示语法中在expressionold_expression的任何位置:

The conditional expression can be used wherever you could use a simple expression in the syntax; that means anywhere it says expression or old_expression in the list display grammar:

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循环的每次迭代) ).

So the first part of a list comprehension, but also the part that produces the outermost iterator (evaluated once), the if expressions, or any of the nested iterators (evaluated each iteration of the next outer for loop).

* 它称为条件表达式;它是 a 三元运算符,但是SQL BETWEEN运算符也是如此.

*It's called the conditional expression; it is a ternary operator, but so is the SQL BETWEEN operator.

这篇关于循环的列表理解+循环的三元运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆