简体   繁体   English

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

[英]Creating a Python list comprehension with an if and break

Is it possible to turn this code into a list comprehension? 是否可以将此代码转换为列表理解?

for i in userInput:
    if i in wordsTask:
        a = i
        break

I know how to convert part of it: 我知道如何转换它的一部分:

[i for i in userInput if i in wordsTask]

But I don't know how to add the break, and the documentation hasn't been much help. 但我不知道如何添加休息,文档也没有多大帮助。

Any help would be appreciated. 任何帮助,将不胜感激。

a = next(i for i in userInput if i in wordsTask)

To break it down somewhat: 要稍微分解一下:

[i for i in userInput if i in wordsTask]

Will produce a list. 会产生一个清单。 What you want is the first item in the list. 你想要的是列表中的第一项。 One way to do this is with the next function: 一种方法是使用下一个功能:

next([i for i in userInput if i in wordsTask])

Next returns the next item from an iterator. Next从迭代器返回下一个项目。 In the case of iterable like a list, it ends up taking the first item. 在像列表一样可迭代的情况下,它最终获取第一个项目。

But there is no reason to actually build the list, so we can use a generator expression instead: 但是没有理由实际构建列表,所以我们可以使用生成器表达式:

a = next(i for i in userInput if i in wordsTask)

Also, note that if the generator expression is empty, this will result in an exception: StopIteration . 另请注意,如果生成器表达式为空,则会导致异常: StopIteration You may want to handle that situation. 您可能想要处理这种情况。 Or you can add a default 或者您可以添加默认值

a = next((i for i in userInput if i in wordsTask), 42)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM