程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python basics] usage of random.shuffle()

編輯:Python

Function usage
random.shuffle() is used to shuffle the elements in a list. It is worth noting that using this method will not generate a new list, but just shuffle the order of the original list.
Code Examples

# shuffle() usage exampleimport randomx = [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]



Source code and comments

def shuffle(self, x, random=None):"""Shuffle list x in place, and return None.Shuffle the list in place, without generating a new list.Optional argument random is a 0-argumentfunction returning a random float in [0.0, 1.0);if it is the default None,the standard random.random will be used.The optional parameter random is a function from 0 to parameter, returning a random floating point in [0.0, 1.0);If random is the default value of None, the standard random.random() will be used."""if random is None:randbelow = self._randbelowfor 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 = intfor 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]


References
[1] Using random.shuffle in python
[2] Using random.shuffle() to shuffle the list order in Python


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved