首页 > 解决方案 > 有没有办法在 Python 的 next 函数中包含多个条件?

问题描述

一般的想法是我想在每个列表中找到满足两个条件中的任何一个的第一个值。IE

a = next((x for x in the_iterable if x > 3), default_value)

但是,我希望它具有多个条件,例如:

a = next((x for x in the_iterable if x > 3 or x-1 for x in the_iterable if x>2), default_value)

我的代码现在看起来像:

a = []
for x in iterable:
  if x>3:
    a.append(x)
    break
  elif x>4:
    a.append(x-1)
    break

标签: pythonconditional-statementsnext

解决方案


您现在的代码更漂亮,但这会起作用:

a = next((
 (x - 1 if x > 4 else x) 
 for x in the_iterable 
 if (x > 3 or x > 4)
), default_value)

推荐阅读