使用random模塊中的sample函數
功能:
random.sample(seq, k)實現從序列或集合seq中隨機選取k個獨立的的元素
參數:
seq:元組、列表或字符串
k:選取元素個數
實例:
In [1]: import random
In [2]: f = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [3]: f
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [4]: random.sample(f, 5)
Out[4]: [5, 3, 6, 9, 4]
使用random模塊中的choice函數
功能:
random.choice(seq)實現從序列或集合seq中隨機選取一個元素
參數:
seq:元組、列表或字符串
實例:
In [1]: import random
In [2]: f = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [3]: f
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [4]: random.choice(f)
Out[4]: 2