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

时间:2011-01-31 17:50:58

标签: python tuples

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

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

3 个答案:

答案 0 :(得分:10)

>>> import random
>>> x = tuple(range(100))
>>> random.choice(x)
8

random.choice

按照S. Lott的要求@Updated:

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))')

输出:

2.73662090302
1.01494002342

答案 1 :(得分:4)

答案 2 :(得分:3)

random.choice()

random.choice(_tuple)