基于范围的Python训练单位成本
我想根据通过的单位计算出单位成本。比如说基于范围的Python训练单位成本,python,django,Python,Django,我想根据通过的单位计算出单位成本。比如说 0-499 = unit cost of 0.049 500-999 = unit cost of 0.050 999+ = unit cost of 0.060 这就是我迄今为止所尝试的: unitCost = 0.049 if self.units <= 499: unitCost = 0.049 elif self.units >= 500: u
0-499 = unit cost of 0.049
500-999 = unit cost of 0.050
999+ = unit cost of 0.060
这就是我迄今为止所尝试的:
unitCost = 0.049
if self.units <= 499:
unitCost = 0.049
elif self.units >= 500:
unitCost = 0.050
elif self.units >= 999:
unitCost = 0.060
else:
unitCost = 0.049
elif
仅在前一个if
为False时进行评估;你的第三个条件永远无法达到
倒过来:
if self.units >= 999:
unitCost = 0.060
elif self.units >= 500:
unitCost = 0.050
else:
unitCost = 0.049
问题是你的if状态。您需要执行类似于
units>=500和units的操作,这可以通过将self.units
键入int
来实现,如果它具有float
值,并执行以下代码段
if int(self.units) in range(0, 500):
unitCost = 0.049
elif int(self.units) in range(500, 1000):
unitCost = 0.050
else:
unitCost = 0.060
它似乎没有达到我所需要的效果,请参见示例。这不是对您问题的准确描述。抱歉,更新的描述可能重复这是最好的方法吗?tho,是否有介于3到130倍之间的中间函数?@Wooble(它使用的是O(n)算法,而不是常数时间算法…)。而且只有当self.units
是整数时才有效,所以只要卖出一半,它就会失败。删除,因为它无论如何都很难看,尽管我觉得xrange在小数点上有一个固定的时间\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
很好。但这仍然不适用于我的例子。我完全偏离了小数点。我还没有喝咖啡。用十进制表示货币价值不是一个坏主意,尽管我怀疑它在这种情况下会起作用;无论如何,你都需要四舍五入到最接近的一美分。我的IDE不喜欢它。lol:它说“这个检查突出了可以简化的链式比较。”我不知道它想要什么。没关系,谢谢。只是为了证明我为什么接受这个答案。你和@Wooble的答案似乎都很完美,如果我能接受这两个答案,我会接受的。但是,我确实从这个答案中学到了很多。在范围(…)中使用
非常慢,因为您要查找的值必须与范围中的每个值进行比较,直到找到正确的值为止。因此,最好使用一个简单的比较,我不知道这一点。谢谢你提供的信息。我将确保在未来的代码中避免使用这些代码。:)
unitCost = 0.049
if units <= 499:
unitCost = 0.049
elif units >= 500 and units <= 999:
unitCost = 0.050
elif units > 999:
unitCost = 0.060
print unitCost
if int(self.units) in range(0, 500):
unitCost = 0.049
elif int(self.units) in range(500, 1000):
unitCost = 0.050
else:
unitCost = 0.060