函数用法
  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()的使用方法

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐