shuffle()函数是将列表的所有元素随机排序。
有时候我们的任务中会使用到随机sample一个数据集的某些数,比如一个文本中,有10行,我们需要随机选取前5个。
那么我们就可以采取shuffle()函数,然后list中放入1-10个行号,利用shuffle()函数之后,序号就打乱了。
这个时候,我们选取前5个元素即可。就起到了随机打乱的结果了。
代码:
# -*- coding: UTF-8 -*- #代码功能是测试一下shuffle()函数 import random number = [] for index in range(1,11): number.append(index) random.shuffle(number) for index in range(5): print number[index]
通过 Fisher-Yates 算法对新列表进行排序,该算法会打乱列表元素的顺序:
from copy import deepcopy from random import randint def shuffle(lst): temp_lst = deepcopy(lst) m = len(temp_lst) while (m): m -= 1 i = randint(0, m) temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] return temp_lst foo = [1,2,3] shuffle(foo) # [2,3,1] , foo = [1,2,3]
下一篇:requests模块怎么用