2011-01-31 6 views

답변

9
>>> import random 
>>> x = tuple(range(100)) 
>>> random.choice(x) 
8 

random.choice

을 @Updated S. Lot가 물었다. t :

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 
+0

하지만이 빨리입니까? 당신이 측정 했습니까? 'timeit'을 사용하여 어느 것이 더 빠름을 보여줄 수 있습니까? –

+0

@S. Lott : – user225312

+0

을 업데이트하면'random.randrange'를 사용하는 것이 더 좋습니다. – SilentGhost

관련 문제