使用if和break创建Python列表理解

sub*_*ray 15 python for-loop if-statement list-comprehension

是否可以将此代码转换为列表理解?

for i in userInput:
    if i in wordsTask:
        a = i
        break
Run Code Online (Sandbox Code Playgroud)

我知道如何转换它的一部分:

[i for i in userInput if i in wordsTask]
Run Code Online (Sandbox Code Playgroud)

但我不知道如何添加休息,文档也没有多大帮助.

任何帮助,将不胜感激.

Win*_*ert 42

a = next(i for i in userInput if i in wordsTask)
Run Code Online (Sandbox Code Playgroud)

要稍微分解一下:

[i for i in userInput if i in wordsTask]
Run Code Online (Sandbox Code Playgroud)

会产生一个清单.你想要的是列表中的第一项.一种方法是使用下一个功能:

next([i for i in userInput if i in wordsTask])
Run Code Online (Sandbox Code Playgroud)

Next从迭代器返回下一个项目.在像列表一样可迭代的情况下,它最终获取第一个项目.

但是没有理由实际构建列表,所以我们可以使用生成器表达式:

a = next(i for i in userInput if i in wordsTask)
Run Code Online (Sandbox Code Playgroud)

另请注意,如果生成器表达式为空,则会导致异常:StopIteration.您可能想要处理这种情况.或者您可以添加默认值

a = next((i for i in userInput if i in wordsTask), 42)
Run Code Online (Sandbox Code Playgroud)

  • 非常好!非常微妙 - 考虑到OP要求帮助学习列表理解,你可能应该解释这里发生了什么. (3认同)
  • 请注意,如果`len(userInput)== 0`可能是'True`,则应通过`next`的第二个参数提供默认值:`a = next((生成器表达式),默认值)` (3认同)
  • 很好,但您忘记了:当生成器表达式不是函数的唯一参数时,要求它有括号。 (3认同)