網站首頁 編程語言 正文
示例.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
相關推薦
- 2022-08-15 使用mybatis-plus 的baseMapper的selectById 出現查詢不到值
- 2022-04-04 react安裝報錯ReactDOM.render is no longer supported in
- 2023-06-05 Qt利用QNetwork實現上傳數據的示例代碼_C 語言
- 2022-11-12 C語言用遞歸函數對素數進行判斷流程_C 語言
- 2022-06-12 Dockerfile文件編寫及構建鏡像命令解析_docker
- 2023-04-20 文本超出顯示省略號在項目中的使用
- 2022-06-02 python獲取字符串中的email_python
- 2022-07-17 關于python通過新建環境安裝tfx的問題_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支