Python random.shuffle() 方法



Python 的 random.shuffle() 方法用於隨機打亂列表的順序。打亂一個物件列表意味著使用 Python 改變給定序列中元素的位置。此方法用於修改原始列表,它不返回新列表。

此方法無法直接訪問,因此我們需要匯入 shuffle 模組,然後需要使用 random 靜態物件呼叫此函式。

語法

以下是 Python random.shuffle() 方法的語法:

random.shuffle(lst)

引數

以下是引數:

  • lst − 這是一個列表。

返回值

此方法不返回任何值。

示例 1

以下示例演示了 Python random.shuffle() 方法的使用。這裡將一個列表作為引數傳遞給 shuffle() 方法。

import random
list = [20, 16, 10, 5];
random.shuffle(list)
print ("Reshuffled list : ",  list)
random.shuffle(list)
print ("Reshuffled list : ",  list)

執行上述程式時,會產生以下結果:

Reshuffled list :  [16, 5, 10, 20]
Reshuffled list :  [16, 5, 20, 10]

示例 2

在下面給出的示例中,一個列表包含運動名稱,另一個列表包含其各自的運動員。現在,我們正在打亂這兩個列表,同時保持相同的打亂順序。

import random
# the first list of sports name
Sports = ['Cricket', 'Tennis', 'Badminton', 'Hockey']
# the second list of sports players
Player = ['Sachin Tendulkar', 'Roger Federer', 'PV Sindhu', 'Dhyan Chand']
# printing the list before shuffle
print("Sports Names before shuffling are: ", Sports)
print("Respective Sports Players before shuffling are: ", Player)
# Shuffling both the lists in same order
mappingIndex = list(zip(Sports, Player))
random.shuffle(mappingIndex)
# making separate list 
List1_sportsName, List2_Players = zip(*mappingIndex)
# printing the list after shuffle
print("Sports Names after shuffling are: ", List1_sportsName)
print("Sports Players after shuffling are: ", List2_Players)
# Sports name and Player at the given index is
print('The sports player of',List1_sportsName[2],'is', List2_Players[2])

執行上述程式碼時,我們得到以下輸出:

Sports Names before shuffling are:  ['Cricket', 'Tennis', 'Badminton', 'Hockey']
Respective Sports Players before shuffling are:  ['Sachin Tendulkar', 'Roger Federer', 'PV Sindhu', 'Dhyan Chand']
Sports Names after shuffling are:  ('Cricket', 'Hockey', 'Badminton', 'Tennis')
Sports Players after shuffling are:  ('Sachin Tendulkar', 'Dhyan Chand', 'PV Sindhu', 'Roger Federer')
The sports player of Badminton is PV Sindhu

示例 3

在下面的示例中,我們建立一個字串“TutorialsPoint”。然後我們將字串轉換為列表。之後,我們使用 shuffle() 方法隨機化字串字元。然後,我們再次將列表轉換為字串並列印結果。

import random
string = "TutorialsPoint"
print('The string is:',string)
# converting the string to list
con_str = list(string)
# shuffling the list
random.shuffle(con_str)
# convert list to string
res_str = ''.join(con_str)
# The shuffled list
print('The list after shuffling is:',res_str)

以下是上述程式碼的輸出:

The string is: TutorialsPoint
The list after shuffling is: nolroiisPTtuta

示例 4

在這裡,range() 函式用於檢索數字序列“num”。然後建立一個該數字範圍的列表。之後,將此“num”作為引數傳遞給 shuffle() 方法。

import random
# creating a list of range of integers
num = list(range(15))
# Shuffling the range of integers
random.shuffle(num)
print('The shuffled integers are:',num)

上述程式碼的輸出如下:

The shuffled integers are: [8, 6, 3, 12, 9, 7, 0, 10, 5, 14, 13, 4, 2, 11, 1]
python_modules.htm
廣告