有没有优雅的替代方法来过滤这些结果而不使用大量的if语句?

2 投票
1 回答
2097 浏览
提问于 2025-04-17 11:03

我正在用Python做一些模拟,生成了1000个结果。每个结果都有多个属性,比如风险、成本等等。

现在我想找出符合特定条件的结果,比如:

Factor 1, cost should be between 10 and 20
Factor 2, risk should be between 0 and 5
Factor 3...
Factor 4...
....

目前我使用了一系列嵌套的if语句来实现这个目标。随着条件越来越多,嵌套的结构变得很复杂。有没有更简单优雅的方法来筛选符合条件的结果呢?

1 个回答

7

有很多解决方案,这些方案取决于你的数据和你喜欢的编码风格。例如:

>>> conditions = (lambda x: 10 < x.cost < 20, lambda x: 0 < x.risk < 10)
>>> filter(lambda x: all(cond(x) for cond in conditions), result)

或者直接这样:

>>> conditions = lambda x: 10 < x.cost < 20 and 0 < x.risk < 10
>>> filter(conditions, result)

或者:

>>> [r for r in result if 10 < r.cost < 20 and 0 < r.risk < 10]

撰写回答