在python3中使用shuffle函數(shù)要注意的地方
1 shuffle函數(shù)與其他函數(shù)不一樣的地方
shuffle函數(shù)沒有返回值!shuffle函數(shù)沒有返回值!shuffle函數(shù)沒有返回值!僅僅是實現(xiàn)了對list元素進行隨機排序的一種功能
請看下面的坑
1.1 誤認為shuffle函數(shù)會有一個返回值的錯誤例子
num1 = list(range(1,39526)) #產生1-39525的數(shù) num2 = random.shuffle(num1) num3 = num2[0:30000] #取前30000個行號的元素 num4 = num2[30000:39524] #取到后面9525個元素
執(zhí)行結果:
File "E:/pythonProj/test2/readDatasetCSVfile.py", line 122, in <module> num3 = num2[0:30000] #取前30000個行號的元素 TypeError: 'NoneType' object is not subscriptable
從這個錯誤中我們也可以看出來,指明obiect沒有類型,其實現(xiàn)在這個num2中是null,什么也沒有,因為shuffle沒有返回值,所以自然會報這種類型的錯誤。
1.2 正確使用shuffle函數(shù)的例子
num1 = list(range(1,39526)) #產生1-39525的數(shù) random.shuffle(num1) #注意shuffle沒有返回值,該函數(shù)完成一種功能,就是對list進行排序打亂 num3 = num1[0:30000] #取前30000個行號的元素 num4 = num1[30000:39524] #取到后面9525個元素
這個時候才順利運行通過!
補充拓展:對python中使用shuffle和permutation對列表進行隨機洗牌的區(qū)別
函數(shù):shuffle將列表的所有元素隨機排序,不生成新的數(shù)組返回
示例:
import random list = [20, 16, 10, 5]; random.shuffle(list) # 參數(shù)只能是列表,元組、字典、字符串會報錯 print("隨機排序列表 : ", list) random.shuffle(list) print("隨機排序列表 : ", list)
執(zhí)行結果:
函數(shù):permutation 返回排列范圍的隨機列表或返回一個新的打亂順序的數(shù)組,并不改變原來的數(shù)組,
如果輸入是一個多維數(shù)組,則它只沿其第一個索引進行無序排列
示例:
import numpy as np new_arr = np.random.permutation(10) print(new_arr) new_arr1 = np.random.permutation([1, 4, 9, 12, 15]) # 參數(shù)為列表 print(new_arr1) arr = np.arange(9).reshape((3, 3)) new_arr2 = np.random.permutation(arr) print(new_arr2) new_arr3 = np.random.permutation([{"a": 1, "b": 2}, [{"e": 5}, {"c": 3}, {"d": 4}], [{"f": 6}, {"g": 8}]])# 子數(shù)組中的排列順序不變 print(new_arr3) new_arr4 = np.random.permutation((1, 4, 9, 12, 15)) #可以傳元組參數(shù) print(new_arr4) import numpy as np new_arr = np.random.permutation(10) print(new_arr) new_arr1 = np.random.permutation([1, 4, 9, 12, 15]) print(new_arr1) arr = np.arange(9).reshape((3, 3)) new_arr2 = np.random.permutation(arr) print(new_arr2) new_arr3 = np.random.permutation([{"a": 1, "b": 2}, [{"e": 5}, {"c": 3}, {"d": 4}], [{"f": 6}, {"g": 8}]]) # 子數(shù)組中的排列順序不變 print(new_arr3)
執(zhí)行結果:
以上這篇在python3中使用shuffle函數(shù)要注意的地方就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。