日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python中random.shuffle()函數(shù)用法代碼案例_python

作者:一窮二白到年薪百萬 ? 更新時間: 2022-12-24 編程語言

函數(shù)用法

??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.
	可選參數(shù)random是一個從0到參數(shù)的函數(shù),返回[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()的使用方法

原文鏈接:https://blog.csdn.net/zfhsfdhdfajhsr/article/details/110290921

欄目分類
最近更新