【问题标题】:If/yield cascade - how to make more concise?If/yield cascade - 如何更简洁?
【发布时间】:2014-10-06 19:32:02
【问题描述】:

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

if condition1:
  yield x
else:
  yield None

if condition2:
  yield y
else:
  yield None

...

有没有办法让这种代码更简洁?

【问题讨论】:

  • yield x if condition1 else None?
  • 你能举例说明你有什么样的条件吗?否则我能想到的就是让它成为一个班轮:yield x if condition1 else None
  • 删除了 switch-statement 标签,因为 Python 没有 switch 语句,如果有的话,我无法想象你会如何期望在这里为你提供帮助。

标签: python if-statement yield


【解决方案1】:

使用conditional expressions 会更简洁:

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

注意:答案的第二部分因以下 cmets 中给出的原因而被删除。

【讨论】:

  • yield from (value if condition else None for value, condition in blah blah)
  • 第二种示例违背了生成器的观点,因为必须在生成器能够产生其第一个值之前评估所有条件和值。 abarnert 的一个班轮也是如此。
  • 在第二个示例中,当然存在将评估条件的大量负载转移到组成列表的单个语句的危险,而不是在收益之间分配负载。当然,只有 OP 才能知道这是否是一个问题。
  • 如果您必须创建一个列表只是为了有一些东西可以迭代,请不要使用 for 循环;它不容易阅读,而且会对性能产生影响。
  • @Dunes:如果条件和值已经在名为xycondition1condition2等的变量中,那么它们已经按照定义提前求值了.如果它们在例如一对任意迭代中,那么您只需执行yield from (value if condition else None for value, condition in zip(values, conditions))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2022-08-19
  • 2011-06-21
相关资源
最近更新 更多