在一个函数中,我有很多连续的语句,如下所示:
if condition1:
yield x
else:
yield None
if condition2:
yield y
else:
yield None
...
有没有办法让这种代码更加简洁?
最佳答案
使用conditional expressions会让它更简洁:
yield x if condition1 else None
yield y if condition2 else None
或者,如果您有许多(值、条件)对并且不介意预先评估所有条件:
for val, cond in [(x, 条件1), (y, 条件2)]:yield val if cond else None
注意:答案的第二部分因下面评论中给出的原因而受到影响。
关于python - if/yield 级联 - 如何使更简洁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223479/