If/yield级联-如何使其更加简洁



在一个函数中,我有很多连续的语句,如下所示:

if condition1:
  yield x
else:
  yield None
if condition2:
  yield y
else:
  yield None
...

有没有一种方法可以使这种代码更加简洁?

使用条件表达式会使其更加简洁:

yield x if condition1 else None
yield y if condition2 else None

或者,如果您有许多(值、条件)对,并且不介意预先评估所有条件:

for val, cond in [(x, condition1), (y, condition2)]:yield val if cond else None

注意:答案的第二部分因以下评论中给出的原因而受损。

最新更新