Python中random.shuffle()函數(shù)用法代碼案例
更新時間:2022年11月25日 14:57:34 作者:一窮二白到年薪百萬
random.shuffle方法,對元素進行重新排序,打亂原有的順序,返回一個隨機序列,該方法的作用類似洗牌,本文重點給大家介紹Python中random.shuffle()函數(shù)用法代碼案例,感興趣的朋友跟隨小編一起看看吧
函數(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]
參考文獻
[2]Python中打亂列表順序 random.shuffle()的使用方法
到此這篇關(guān)于Python中random.shuffle()的用法的文章就介紹到這了,更多相關(guān)python random.shuffle()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3.5常見內(nèi)置方法參數(shù)用法實例詳解
這篇文章主要介紹了Python3.5常見內(nèi)置方法參數(shù)用法,結(jié)合實例形式詳細分析了Python常見的內(nèi)置方法及參數(shù)使用技巧,需要的朋友可以參考下2019-04-04