在python中获取随机布尔值? [英] Get a random boolean in python?

查看:432
本文介绍了在python中获取随机布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最好的方法(快速而优雅)来获取python中的随机布尔值(翻转硬币).

I am looking for the best way (fast and elegant) to get a random boolean in python (flip a coin).

目前我正在使用random.randint(0, 1)random.getrandbits(1).

还有我不知道的更好的选择吗?

Are there better choices that I am not aware of?

推荐答案

Adam的回答相当快,但是我发现random.getrandbits(1)要快得多.如果您真的想要布尔值而不是long值,那么

Adam's answer is quite fast, but I found that random.getrandbits(1) to be quite a lot faster. If you really want a boolean instead of a long then

bool(random.getrandbits(1))

的速度仍然是random.choice([True, False])

两个解决方案都需要import random

如果速度不是最高优先级,那么random.choice绝对读起来更好

If utmost speed isn't to priority then random.choice definitely reads better

$ python -m timeit -s "import random" "random.choice([True, False])"
1000000 loops, best of 3: 0.904 usec per loop
$ python -m timeit -s "import random" "random.choice((True, False))" 
1000000 loops, best of 3: 0.846 usec per loop
$ python -m timeit -s "import random" "random.getrandbits(1)"
1000000 loops, best of 3: 0.286 usec per loop
$ python -m timeit -s "import random" "bool(random.getrandbits(1))"
1000000 loops, best of 3: 0.441 usec per loop
$ python -m timeit -s "import random" "not random.getrandbits(1)"
1000000 loops, best of 3: 0.308 usec per loop
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
1000000 loops, best of 3: 0.262 usec per loop  # not takes about 20us of this

在看到@Pavel的答案后添加了这个

Added this one after seeing @Pavel's answer

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.115 usec per loop

这篇关于在python中获取随机布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆