Python random.shuffle()打乱字典排序

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python random.shuffle()打乱字典排序

程序遇上智能星空   2022-09-29 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们