2016-02-28 147 views
-2

我很好奇:Python如何從一個集合中實現random.choice()?Python如何從集合中實現random.choice()?

我可以想象一個非常緩慢的解決方案:選擇1和len(set)之間的數字n,然後重複n次並返回項目。

+2

你有沒有真正嘗試做'random.choice()'一組?你會發現不支持這些設置。 – mhawke

+2

https://github.com/python/cpython/blob/master/Lib/random.py#L250-L256 – Lol4t0

回答

4

random.choice()實際上並不支持集:

>>> import random 
>>> s = {1, 2, 3, 4, 5} 
>>> random.choice(s) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib64/python3.4/random.py", line 256, in choice 
    return seq[i] 
TypeError: 'set' object does not support indexing 

你可以,但是,設置轉換到一個列表:

>>> random.choice(list(s)) 
2 
1

集不支持對象的索引。所以你需要轉換。 使用一個元組,而不是一個列表是更有效的實例:

s = set([1, 2, 3, 4, 5, 6]) 
print random.choice(tuple(s)) 

如果您正在尋找清晰,另一種選擇是使用樣品。然而,它在內部並不是非常有效,因爲它無論如何都會轉換爲第一個示例。

s = set([1, 2, 3, 4, 5, 6]) 
print random.sample(s, 1) 

裁判: Are tuples more efficient than lists in Python?