详解Python中打乱列表顺序random.shuffle()的使用方法


Posted in Python onNovember 11, 2019

之前自己一直使用random中 randint生成随机数以及使用for将列表中的数据遍历一次。

现在有个需求需要将列表的次序打乱,或者也可以这样理解:

【需求】将一个容器中的数据每次随机逐个遍历一遍。

random.shuffle()方法提供了完美的解决方案。

不会生成新的列表,只是将原列表的次序打乱

# shuffle()使用样例
import random

x = [i for i in range(10)]
print(x)
random.shuffle(x)
print(x)

源码及注释(个人翻译注释)

def shuffle(self, x, random=None):
  """Shuffle list x in place, and return None.
  原位打乱列表,不生成新的列表。

  Optional argument random is a 0-argument
  function returning a random float in [0.0, 1.0); 
  if it is the default None, 
  the standard random.random will be used.
 可选参数random是一个从0到参数的函数,返回[0.0,1.0)中的随机浮点;
 如果random是缺省值None,则将使用标准的random.random()。
  """

  if random is None:
    randbelow = self._randbelow
    for i in reversed(range(1, len(x))):
      # pick an element in x[:i+1] with which to exchange x[i]
      j = randbelow(i + 1)
      x[i], x[j] = x[j], x[i]
  else:
    _int = int
    for i in reversed(range(1, len(x))):
      # pick an element in x[:i+1] with which to exchange x[i]
      j = _int(random() * (i + 1))
      x[i], x[j] = x[j], x[i]

random 中其他的方法

class Random(_random.Random):

  ## -------------------- integer methods -------------------
  def randrange(self, start, stop=None, step=1, _int=int):

  def randint(self, a, b):

  def _randbelow(self, n, int=int, maxsize=1 << BPF, type=type,
          Method=_MethodType, BuiltinMethod=_BuiltinMethodType):

  ## -------------------- sequence methods -------------------
  def choice(self, seq):

  def shuffle(self, x, random=None):

  def sample(self, population, k):

  def choices(self, population, weights=None, *, cum_weights=None, k=1):

  ## -------------------- uniform distribution -------------------
  def uniform(self, a, b):

  ## -------------------- triangular --------------------
  def triangular(self, low=0.0, high=1.0, mode=None):

  ## -------------------- normal distribution --------------------
  def normalvariate(self, mu, sigma):

  ## -------------------- lognormal distribution --------------------
  def lognormvariate(self, mu, sigma):

  ## -------------------- exponential distribution --------------------
  def expovariate(self, lambd):

  ## -------------------- von Mises distribution --------------------
  def vonmisesvariate(self, mu, kappa):

  ## -------------------- gamma distribution --------------------
  def gammavariate(self, alpha, beta):

  ## -------------------- Gauss (faster alternative) --------------------
  def gauss(self, mu, sigma):

  def betavariate(self, alpha, beta):

  ## -------------------- Pareto --------------------
  def paretovariate(self, alpha):

  ## -------------------- Weibull --------------------
  def weibullvariate(self, alpha, beta):

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用mailbox打印电子邮件的方法
Apr 30 Python
Python实现二叉堆
Feb 03 Python
浅谈Python中用datetime包进行对时间的一些操作
Jun 23 Python
使用DataFrame删除行和列的实例讲解
Apr 08 Python
Python实现决策树C4.5算法的示例
May 30 Python
Python实现性能自动化测试竟然如此简单
Jul 30 Python
python os.path.isfile()因参数问题判断错误的解决
Nov 29 Python
kafka-python 获取topic lag值方式
Dec 23 Python
Python如何实现FTP功能
May 28 Python
如何在pycharm中安装第三方包
Oct 27 Python
python绘图pyecharts+pandas的使用详解
Dec 13 Python
Python采集壁纸并实现炫轮播
Apr 30 Python
基于Python实现ComicReaper漫画自动爬取脚本过程解析
Nov 11 #Python
Python多继承以及MRO顺序的使用
Nov 11 #Python
python 有效的括号的实现代码示例
Nov 11 #Python
Python+OpenCV实现实时眼动追踪的示例代码
Nov 11 #Python
python的pyecharts绘制各种图表详细(附代码)
Nov 11 #Python
python OpenCV GrabCut使用实例解析
Nov 11 #Python
Python上下文管理器用法及实例解析
Nov 11 #Python
You might like
德生PL550的电路分析
2021/03/02 无线电
Zend公司全球首推PHP认证
2006/10/09 PHP
destoon数据库表说明汇总
2014/07/15 PHP
filemanage功能中用到的lib.js
2007/04/08 Javascript
用js实现的检测浏览器和系统的函数
2009/04/09 Javascript
基于jquery ajax 用户无刷新登录方法详解
2012/04/28 Javascript
jquery实现的横向二级导航效果代码
2015/08/26 Javascript
javascript实现uploadify上传格式以及个数限制
2015/11/23 Javascript
详解JavaScript中数组的reduce方法
2016/12/02 Javascript
Vue2.0 实现单选互斥的方法
2018/04/13 Javascript
Vue-cli@3.0 插件系统简析
2018/09/05 Javascript
基于vue和react的spa进行按需加载的实现方法
2018/09/29 Javascript
[01:24:34]2014 DOTA2华西杯精英邀请赛5 24 DK VS LGD
2014/05/25 DOTA
[00:32]DOTA2上海特级锦标赛 COL战队宣传片
2016/03/04 DOTA
用Python编写分析Python程序性能的工具的教程
2015/04/01 Python
Python生成器(Generator)详解
2015/04/13 Python
python通过ftplib登录到ftp服务器的方法
2015/05/08 Python
python日志记录模块实例及改进
2017/02/12 Python
Python使用sklearn实现的各种回归算法示例
2019/07/04 Python
python正则爬取某段子网站前20页段子(request库)过程解析
2019/08/10 Python
Python 用turtle实现用正方形画圆的例子
2019/11/21 Python
在python中计算ssim的方法(与Matlab结果一致)
2019/12/19 Python
python实现斗地主分牌洗牌
2020/06/22 Python
Strawberrynet草莓网新加坡站:护肤、彩妆、香水及美发产品
2018/08/31 全球购物
SportsDirect.com马来西亚:英国第一体育零售商
2018/11/21 全球购物
广告设计专业自荐信范文
2013/11/14 职场文书
电子商务应届生求职信
2013/11/16 职场文书
平面设计师工作职责范文
2013/12/03 职场文书
个人委托书范本
2014/04/02 职场文书
开学寄语大全
2014/04/08 职场文书
无犯罪记录证明
2014/09/19 职场文书
放弃继承权公证书
2015/01/23 职场文书
五四青年节活动总结
2015/02/10 职场文书
2015年社区工作总结
2015/04/08 职场文书
《七月的天山》教学反思
2016/02/19 职场文书
优秀创业计划书分享
2019/07/19 职场文书