Python:如何在40%的时间内使变量成为真

时间:2013-08-07 08:09:15

标签: python django django-views

以下最佳方法是什么......

在Django中,我有一个名为' showItem'的变量的视图。可以是truefalse。我想将showItem设置为真正 40%的时间和错误 60%的时间,以及稍后更改这些赔率的选项。

使用Python我应该怎么做?

部分观点:

 def get_context_data(self, **kwargs):
        context = super(EntryDetail, self).get_context_data(**kwargs)
        context['showItem'] = (odds?????)
        return context

2 个答案:

答案 0 :(得分:6)

这是另一种方法:

import random

cur_num   = random.random()
threshold = 0.4

# showItem is true 60 % of the time
showItem = cur_num >= threshold

如果您选择稍后更改阈值,则只需修改threshold变量,这比列出的其他方法更容易。

答案 1 :(得分:2)

import random
num = random.randint(0, 4)
context['showItem'] = True if num <= 1 else False

在这里,我认为@ Xaranke的答案更好,更灵活。 我还测试了笔记本电脑上randomrandint的性能,前者速度提高了10倍。