Python中shuffle函數


shuffle() 方法將序列的所有元素隨機排序。

下面是語法:

1 import random
2 
3 random.shuffle (lst )
lst可以是序列或者元組;
 1 >>> import random;
 2 >>> indexList=[1,2,4,5,8,6];
 3 >>> indexList
 4 [1, 2, 4, 5, 8, 6]
 5 >>> random.shuffle(indexList)
 6 >>> indexList
 7 [1, 2, 4, 5, 8, 6]
 8 >>> random.shuffle(indexList)
 9 >>> indexList
10 [6, 2, 4, 5, 1, 8]
11 >>> random.shuffle(indexList)
12 >>> indexList
13 [2, 1, 4, 5, 6, 8]

 如果是'range'類型,則產生錯誤:

 1 >>> indexList=range(10);
 2 >>> type(indexList)
 3 <class 'range'>
 4 >>> random.shuffle(indexList)
 5 Traceback (most recent call last):
 6   File "<pyshell#28>", line 1, in <module>
 7     random.shuffle(indexList)
 8   File "D:\softwareTool\Python\anzhuang_file\lib\random.py", line 272, in shuffle
 9     x[i], x[j] = x[j], x[i]
10 TypeError: 'range' object does not support item assignment

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM