示例.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方法没有返回值,不会生成新的列表,只是将原列表的顺序随机打乱。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)