gpt4 book ai didi

python - 我什么时候应该更喜欢 random.choice() 而不是 random.randint?

转载 作者:行者123 更新时间:2023-12-04 00:18:32 24 4
gpt4 key购买 nike

考虑从消息列表中打印随机字符串的以下两个选项:

import random

messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']


print(messages[random.randint(0, len(messages) - 1)]) # option 1

print(random.choice(messages)) # option 2

选项 1 和选项 2 产生相同的效果。有理由偏爱其中一个吗?性能怎么样?一个比另一个更有效吗?

最佳答案

一些时间分析:

from timeit import timeit

setup = """
import random
import string
s = string.ascii_lowercase
x = [s[:random.randint(1, 26)] for _ in range(10_000)]
"""
stmt1 = """
random.choice(x)
"""

stmt2 = """
x[random.randint(0, len(x) - 1)]
"""

for i in range(0, 100_000, 10_000):
print(f"Size_seq: {i}")
print(f" choice: {timeit(stmt = stmt1, setup = setup, number = i):>.5}s")
print(f" randint: {timeit(stmt = stmt2, setup = setup, number = i):>.5}s")

输出:

Size_seq: 0
choice: 1.426e-06s
randint: 1.672e-06s
Size_seq: 10000
choice: 0.010363s
randint: 0.017393s
Size_seq: 20000
choice: 0.020168s
randint: 0.034601s
Size_seq: 30000
choice: 0.030942s
randint: 0.050896s
Size_seq: 40000
choice: 0.041753s
randint: 0.069362s
Size_seq: 50000
choice: 0.053554s
randint: 0.088815s
Size_seq: 60000
choice: 0.067187s
randint: 0.10979s
Size_seq: 70000
choice: 0.080606s
randint: 0.12793s
Size_seq: 80000
choice: 0.083252s
randint: 0.1365s
Size_seq: 90000
choice: 0.091724s
randint: 0.14603s

这种差异在大范围内是显着的。因此,如果输入不是很大,您可以使用它们中的任何一个,但是当大小增加时,randint 比 random.choice 慢得多。

关于python - 我什么时候应该更喜欢 random.choice() 而不是 random.randint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62349754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com