python 隨機選取列表中的元素
阿新 • • 發佈:2018-12-12
使用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