网络编程
位置:首页>> 网络编程>> Python编程>> Python使用random.shuffle()随机打乱字典排序

Python使用random.shuffle()随机打乱字典排序

作者:程序遇上智能星空  发布时间:2021-05-02 03:12:01 

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

来源:https://blog.csdn.net/kevinjin2011/article/details/126268970

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com