你能做得比这个基本的实现更好:
import random
def get_random_element(_tuple):
return _tuple[randint(0, len(_tuple) - 1)]
答案 0 :(得分:10)
>>> import random
>>> x = tuple(range(100))
>>> random.choice(x)
8
按照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)
使用random.choice:http://docs.python.org/library/random.html#random.choice
答案 2 :(得分:3)
random.choice(_tuple)