获取元组中随机元素的最快方法是什么?(python)

2 投票
3 回答
10556 浏览
提问于 2025-04-16 10:57

你能做得比这个基本的实现更好吗:

import random
def get_random_element(_tuple):
    return _tuple[randint(0, len(_tuple) - 1)]

3 个回答

3

random.choice() 是一个Python库中的函数,用来从一个列表中随机选择一个元素。

random.choice(_tuple)
16
>>> import random
>>> x = tuple(range(100))
>>> random.choice(x)
8
def first(_tuple):
    return _tuple[randint(0, len(_tuple) - 1)]

def second(_tuple):
    return choice(_tuple)

print timeit('first(t)', 'from __main__ import first; t = tuple(range(10))')        
print timeit('second(t)', 'from __main__ import second; t = tuple(range(10))')

random.choice

这是一个关于 Python 中的 random.choice 函数的链接,能够帮助你从一个列表中随机选择一个元素。

@根据 S. Lott 的要求进行了更新:

输出:

2.73662090302
1.01494002342

撰写回答