繁体   English   中英

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

[英]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()

random.choice(_tuple)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM