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方法没有返回值,不会生成新的列表,只是将原列表的顺序随机打乱。

到此这篇关于Python使用random.shuffle()随机打乱字典排序的文章就介绍到这了,更多相关Python random.shuffle()打乱字典排序内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!

推荐阅读