1 # 1.使用python random模塊的choice方法隨機選擇某個元素 2 import random 3 4 foo = ['a', 'b', 'c', 'd', 'e'] 5 from random import choice 6 7 print(choice(foo)) 8 9 # 2.使用python random模塊的sample函數從列表中隨機選擇一組元素 10 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 11 # 設置種子使得每次抽樣結果相同 12 random.seed(10) 13 slice = random.sample(list, 5) # 從list中隨機獲取5個元素,做爲一個片段返回 14 15 print(slice) 16 print(list) # 原有序列並無改變。
轉載:https://blog.csdn.net/liu3237/article/details/48416969python