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

Bre*_*mas 0 python tuples

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

import random
def get_random_element(_tuple):
    return _tuple[randint(0, len(_tuple) - 1)]
Run Code Online (Sandbox Code Playgroud)

use*_*312 11

>>> import random
>>> x = tuple(range(100))
>>> random.choice(x)
8
Run Code Online (Sandbox Code Playgroud)

random.choice

@更新按照S. Lott的要求:

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))')
Run Code Online (Sandbox Code Playgroud)

输出:

2.73662090302
1.01494002342
Run Code Online (Sandbox Code Playgroud)