Python三元表达式

时间:2017-07-18 23:02:24

标签: python ternary-operator

所以这是使用Java中的1行三元表达式创建和赋值的简单对象。

Interval newInterval = previous.end <= current.end ? new Interval(previous.start, current.end : new Interval(previous.start, previous.end)

等效的python是,

new_interval = Interval(previous.start, current.end) if previous.end <= current.end else Interval(previous.start, previous.end)

我的问题是有更多的pythonic方式来写这个吗?

2 个答案:

答案 0 :(得分:6)

我想要的形式可能是

new_interval = Interval(previous.start, max(current.end, previous.end))

答案 1 :(得分:2)

这更像是Pythonic:

start = previous.start
end = max(current.end, previous.end)
new_interval = Interval(start, end)