【Python基础】random.shuffle()的用法

函数用法
  random.shuffle()用于将一个列表中的元素打乱顺序,值得注意的是使用这个方法不会生成新的列表,只是将原列表的次序打乱
代码案例

# shuffle()使用样例
import random

x = [i for i in range(10)]
print(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(x)
print(x)
[2, 5, 4, 8, 0, 3, 7, 9, 1, 6]

源码及注释

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]

参考文献
[1]python中random.shuffle 使用
[2]Python中打乱列表顺序 random.shuffle()的使用方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值