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

 

posted @ 2014-12-16 23:02  志者之梦  阅读(8324)  评论(0编辑  收藏  举报