易百教程

16、举个 shuffle() 方法的例子?

此方法随机播放给定的字符串或数组。 它随机化数组中的项目。 此方法存在于随机模块中。 因此,需要导入它,然后才能调用该函数。 每次函数调用并产生不同的输出时,它都会打乱元素。

例子:

# import the random module  
import random  
# declare a list  
sample_list1 = ['Z', 'Y', 'X', 'W', 'V', 'U']  
print("Original LIST1: ")  
print(sample_list1)  
# first shuffle   
random.shuffle(sample_list1)  
print("\nAfter the first shuffle of LIST1: ")  
print(sample_list1)  
# second shuffle  
random.shuffle(sample_list1)  
print("\nAfter the second shuffle of LIST1: ")  
print(sample_list1)

运行结果:

Original LIST1: 
['Z', 'Y', 'X', 'W', 'V', 'U']

After the first shuffle of LIST1: 
['V', 'U', 'W', 'X', 'Y', 'Z']

After the second shuffle of LIST1: 
['Z', 'Y', 'X', 'U', 'V', 'W']