这篇文章主要讲解了“Python怎么使用random.shuffle()随机打乱字典排序”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python怎么使用random.shuffle()随机打乱字典排序”吧!
示例.1
import random from random import shuffle x = [[i] for i in range(10)] shuffle(x) print(x)
运行结果:
[[1], [2], [5], [0], [7], [9], [3], [8], [4], [6]]
[[6], [0], [7], [1], [3], [9], [5], [2], [4], [8]]
示例.2
dicts = {
    "productCode": "xyd",
    "account": "phone",
    "appType": "ios",
    "channelCode": "AppStore",
    "event": "FORGET_PWD"
}
 
def random_dic(dicts):
    dict_key_ls = list(dicts.keys())
    random.shuffle(dict_key_ls)
    new_dic = {}
    for key in dict_key_ls:
        new_dic[key] = dicts.get(key)
    return new_dic
 print(random_dic(dicts))运行结果:
{'channelCode': 'AppStore', 'productCode': 'xyd', 'appType': 'ios', 'event': 'FORGET_PWD', 'account': 'phone'}
{'event': 'FORGET_PWD', 'account': 'phone', 'productCode': 'xyd', 'appType': 'ios', 'channelCode': 'AppStore'}
PS:random.shuffle()打乱列表元素顺序
有时候,我们需要将列表中的元素随机打乱顺序,其实只需要使用random库提供的shuffle方法即可,不需要自己额外编写函数。
#!/usr/bin/env python # -*- coding:utf-8 -*- import random if __name__ == '__main__': a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 使用shuffle方法打乱a列表的顺序,无返回值 random.shuffle(a) print(a)
输出:
[9, 5, 2, 8, 6, 7, 1, 10, 4, 3]
Process finished with exit code 0
注意,shuffle方法没有返回值,不会生成新的列表,只是将原列表的顺序随机打乱。