用if和break创建Python列表理解 [英] Creating a Python list comprehension with an if and break

查看:129
本文介绍了用if和break创建Python列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for user input:
if i in wordsTask:
a = i
break

我知道如何将部分它:

  [我为我在userInput中,如果我在wordsTask] 

但是我不知道如何添加break,文档也没有太大的帮助。


解决方案

a = next(i for i在用户输入,如果我在wordsTask)

有点分解:

  [我为我在userInput,如果我在wordsTask] 

会产生一个列表。你想要的是列表中的第一项。一种方法是使用下一个函数:

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

接下来从一个迭代器返回下一个项目。在像列表一样迭代的情况下,它最终取得了第一个项目。

但是没有理由建立这个列表,所以我们可以使用一个生成器表达式而不是:

  a = next(我为我在userInput如果我在wordsTask)

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

  a = next((我为我在userInput,如果我在wordsTask中),42)


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. 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. 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)

这篇关于用if和break创建Python列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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