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
广告