Usage of random module shuffle() in python

今天需要根据字典生成一个随机排列的列表,字典为mydict,列表为mylist。

Execute the following code:

import random
mydict = {'one':'Gao','two':'Wu','three':'Wang','four':'zhao'}
mylist = random.shuffle(mydict)

The following error is prompted:
Traceback (most recent call last):
File “<pyshell#23>”, line 1, in
mydict = random.shuffle(mydict)
File “C:\Program Files\Python311\Lib\random.py”, line 380, in shuffle
x[i], x[j] = x[j], x[i]
After checking the information, it is found that shuffle() only supports random sorting of the list.
Therefore, modify the code as follows:

import random
mydict = {'one':'Gao','two':'Wu','three':'Wang','four':'zhao'}
mylist = random.shuffle(list(mydict))
print(mylist)

Output:
None

After several attempts, None was output, and after looking at the data, I found out that the correct output of shuffle() is None.
So how do you get a randomly sorted list?
After searching the information, it is found that shuffle() is a destructive operation. You can directly rearrange the list as an argument instead of assigning it to another variable. Therefore, modify the code as follows:

import random
mylist = list(mydict)  #取得字典的键列表,也可使用:mylist = mydict.keys()
print(mylist)  #输出:['one', 'two', 'three', 'four']
random.shuffle(mylist)   # 直接将mylist列表修改为随机排列
print(mylist)   # 显示随机排列后的mylist列表:['one', 'three', 'two', 'four']

Finally got the desired random permutation.
At this point, how to get shuffle() to destroy the previous arrangement, you have to execute it again:

mylist = list(mydict)

That is to say, mylist cannot restore the original arrangement after the shuffle() operation, but can only be regenerated.
By the way, if you want to get the list of values ​​​​of the dictionary, you can execute:

mylist =mydict.values()

Guess you like

Origin blog.csdn.net/any1where/article/details/128237221