[英]What is the fastest way to check for existence and get random element from data structure in python?
[英]What's the fastest way to get a random element from a tuple? (python)
您能否比此基本实现做得更好:
import random
def get_random_element(_tuple):
return _tuple[randint(0, len(_tuple) - 1)]
>>> import random
>>> x = tuple(range(100))
>>> random.choice(x)
8
@按照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))')
输出:
2.73662090302
1.01494002342
使用random.choice: http ://docs.python.org/library/random.html#random.choice
random.choice(_tuple)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.