如果在一行中没有列表理解 [英] for-if without list comprehension in one line

查看:92
本文介绍了如果在一行中没有列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在没有列表理解的情况下将其写成一行吗?

can this be written in one line without List Comprehensions?

for x in vec: 
    if x > 3:
         ...
         ...

推荐答案

请参阅@KennyTM ...没有理由压缩那么多.

See @KennyTM... no reason to compress that much.

所说的话,for x in (i in vec if i > 3)以及itertools.ifilter(或者只是Python 3中的内置filter)都具有lambda x: x > 3谓词.它们同样适用于所有可迭代对象,并且很懒惰(例如,如果您在循环中break,那么您对单个项目的检查就不会太多).

What being said, for x in (i in vec if i > 3) does the job, as well as itertools.ifilter (or just the builtin filter in Python 3) with a lambda x: x > 3 predicate. They work with all iterables as well, and are lazy (e.g. if you break during the loop, you didn't check a single item too much).

这篇关于如果在一行中没有列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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