[英]Is there an easy way to write this in Python?
if(i-words < 0):
start_point = 0
else:
start_point = i - words
Or is this the easiest way using min/max?或者这是使用最小值/最大值的最简单方法? This is for lists splicing.这是用于列表拼接。
I want start_point to always be 0 or above.我希望 start_point 始终为 0 或更高。
Better is to make the limiting more obvious更好的是使限制更明显
start_point = max(i - words, 0)
This way, anyone reading can see that you're limiting a value.这样,任何阅读的人都可以看到您正在限制一个值。
Using any form of if
has the disadvantage that you compute twice i - words
.使用任何形式的if
都有一个缺点,即计算两次i - words
。 Using a temporary for this will make more code bloat.为此使用临时代码会使代码膨胀。
So, use max
and min
in these cases.因此,在这些情况下使用max
和min
。
How about怎么样
start_point = 0 if i - words < 0 else i - words
or或者
start_point = i - words if i - words < 0 else 0
or even better, the clearest way:甚至更好,最清晰的方法:
start_point = max(i - words, 0)
As Mihai says in his comment, the last way is not only clearer to read and write, but evaluates the value only once, which could be important if it's a function call.正如 Mihai 在他的评论中所说,最后一种方法不仅读写更清晰,而且只评估一次值,如果它是 function 调用,这可能很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.