python - Python 中的条件 for

标签 python

Python 有没有类似下面的东西?

for item in items #where item>3:
  #.....

我的意思是 Python 2.7 和 Python 3.3 一起。

最佳答案

您可以将循环与 generator expression 结合使用:

for x in (y for y in items if y > 10):
    ....

itertools.ifilter (py2)/filter (py3) 是另一种选择:

items = [1,2,3,4,5,6,7,8]

odd = lambda x: x % 2 > 0

for x in filter(odd, items):
    print(x)

关于python - Python 中的条件 for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986996/

相关文章:

python - 如何在 Python 3.5 中使用 async/await?

python - 如何访问通过 Django 表单上传的媒体文件?

python - 使用 while 循环的基本多处理

python列表和变量到html模板

python - 使用python从post body请求中提取json数据

python - 如何返回包含公共(public)元素且不重复的列表

python - 强化算法似乎可以学习,但脚本卡住并且代理没有重置

python - 如何通过 sqlalchemy 在多个(生成的)python 进程中使用 sqlite

python - model.predict 导致 oom 问题,但 model.fit 不会 :

python - matplotlib 中的自动缩放,在同一图表中绘制不同的时间序列