What's the fastest way to get a random element from a tuple? (python)
Can you do better than this basic implementation:
import random
def get开发者_JS百科_random_element(_tuple):
return _tuple[randint(0, len(_tuple) - 1)]
>>> import random
>>> x = tuple(range(100))
>>> random.choice(x)
8
random.choice
@Updated as asked by 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))')
Output:
2.73662090302
1.01494002342
Use random.choice: http://docs.python.org/library/random.html#random.choice
random.choice()
random.choice(_tuple)
精彩评论