Python中的 random.shuffle()函数
shuffle()是 random 模块的内置方法。它用于打乱序列(列表)。改组意味着改变序列元素的位置。在这里,洗牌操作就位。
随机.shuffle()
Syntax : random.shuffle(sequence, function)
Parameters :
- sequence : can be a list
- function : optional and by default is random(). It should return a value between 0 and 1.
Returns : nothing
示例 1:随机播放列表
Python3
# import the random module
import random
# declare a list
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
Python3
# import the random module
import random
# user defined function to shuffle
def sample_function():
return 0.5
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
# as sample_function returns the same value
# each time, the order of shuffle will be the
# same each time
random.shuffle(sample_list, sample_function)
print("\nAfter the first shuffle : ")
print(sample_list)
sample_list = ['A', 'B', 'C', 'D', 'E']
random.shuffle(sample_list, sample_function)
print("\nAfter the second shuffle : ")
print(sample_list)
输出 :
Original list :
['A', 'B', 'C', 'D', 'E']
After the first shuffle :
['A', 'B', 'E', 'C', 'D']
After the second shuffle :
['C', 'E', 'B', 'D', 'A']
shuffle() 方法不能用于对字符串等不可变数据类型进行混洗。
示例 2:
Python3
# import the random module
import random
# user defined function to shuffle
def sample_function():
return 0.5
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
# as sample_function returns the same value
# each time, the order of shuffle will be the
# same each time
random.shuffle(sample_list, sample_function)
print("\nAfter the first shuffle : ")
print(sample_list)
sample_list = ['A', 'B', 'C', 'D', 'E']
random.shuffle(sample_list, sample_function)
print("\nAfter the second shuffle : ")
print(sample_list)
输出 :
Original list :
['A', 'B', 'C', 'D', 'E']
After the first shuffle :
['A', 'D', 'B', 'E', 'C']
After the second shuffle :
['A', 'D', 'B', 'E', 'C']