简体   繁体   English

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

[英]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_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: @按照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

使用random.choice: http ://docs.python.org/library/random.html#random.choice

random.choice()

random.choice(_tuple)

暂无
暂无

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

相关问题 在python中检查存在并从数据结构中获取随机元素的最快方法是什么? - What is the fastest way to check for existence and get random element from data structure in python? 在python中查找列表中列表元素的最快方法是什么? - What's the fastest way to locate a list element within a list in python? 用python中元组列表中元组的第一个元素索引元素的最快方法 - Fastest way to index an element by the first element of a tuple in a list of tuples in python 从Python字典中获取任意元素的最快方法是什么? - What is the fastest way to get an arbitrary element out of a Python dictionary? 在python中,生成元组的最快方法是什么:(1.0,0.0,0.0,2.0,0.0,0.0,…,N,0.0,0.0)? - In python what's the fastest way to generate the tuple: (1.0, 0.0, 0.0, 2.0, 0.0, 0.0, …, N, 0.0, 0.0)? Python获取元素数组的最快方法 - Python fastest way to gets element's array 在 Python 列表中大量查找随机索引的最快方法是什么? - What's the fastest way of finding a random index in a Python list, a large number of times? Django,什么是最好的,最快的方式来获得第一个和最后一个元素,Customer.objects.xxxx - Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx 在python中扩展URL的最快方法是什么 - What's the fastest way to expand url in python 在 Python 中解析 arguments 的最快方法是什么? - What's the fastest way to parse arguments in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM