在python中获取一个随机布尔值? [英] Get a random boolean in 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)
.
For the moment I am using random.randint(0, 1)
or 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.
请注意,由于属性查找,random.choice()
比 choice()
慢(在 from random import choice
之后).
Note that random.choice()
is slower than just choice()
(after from random import choice
) due to the attribute lookup.
$ python3 --version
Python 3.9.7
$ python3 -m timeit -s "from random import choice" "choice([True, False])"
1000000 loops, best of 5: 376 nsec per loop
$ python3 -m timeit -s "from random import choice" "choice((True, False))"
1000000 loops, best of 5: 352 nsec per loop
$ python3 -m timeit -s "from random import getrandbits" "getrandbits(1)"
10000000 loops, best of 5: 33.7 nsec per loop
$ python3 -m timeit -s "from random import getrandbits" "bool(getrandbits(1))"
5000000 loops, best of 5: 89.5 nsec per loop
$ python3 -m timeit -s "from random import getrandbits" "not getrandbits(1)"
5000000 loops, best of 5: 46.3 nsec per loop
$ python3 -m timeit -s "from random import random" "random() < 0.5"
5000000 loops, best of 5: 46.4 nsec per loop
这篇关于在python中获取一个随机布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!