網站首頁 編程語言 正文
在python中,通常通過dict
和zip
組合來構建鍵值對。
比如:
aid = [i for i in range(10)] name = [[1] * 3] * len(aid) dic1 = dict(zip(aid,name)) print('dic1:', dic1)
得到:
{0: [1, 1, 1],
1: [1, 1, 1],
2: [1, 1, 1],
3: [1, 1, 1],
4: [1, 1, 1],
5: [1, 1, 1],
6: [1, 1, 1],
7: [1, 1, 1],
8: [1, 1, 1],
9: [1, 1, 1]}
這樣建立的是aid
和name
的一一映射關系,將aid作為key,第二列作為value。。
還可以通過dic
函數的形式或者{}
直接構造
dic2 = {'aid': aid,'name':name} print('\ndic2:',dic2)
{
‘aid’: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
‘name’: [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
}
這樣通過建立新的key,list作為value存儲。
以上兩種方法,如果想經過aid進行索引取對應值的話:
方法1可以直接取出,方法2還需要獲取到index再進行取值。所以法1速度更快但是與之相對的,法1存儲了很多個key-value對,在存儲空間上不如法2。
空間占用測試如下:
aid = [i for i in range(10)] name = [[1] * 3] * len(aid) dic1 = dict(zip(aid,name)) dic2 = {'aid': aid,'name':name} print('dic1:', dic1) print(sys.getsizeof(dic1)) print('\ndic2:',dic2) print(sys.getsizeof(dic2))
dic1: {0: [1, 1, 1], 1: [1, 1, 1], 2: [1, 1, 1], 3: [1, 1, 1], 4: [1, 1, 1], 5: [1, 1, 1], 6: [1, 1, 1], 7: [1, 1, 1], 8: [1, 1, 1], 9: [1, 1, 1]} 360 dic2: {'aid': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'name': [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]} 232
經過測試,字典占用空間和鍵值對的個數并不是線性的。如果在很大的數據中,就需要考慮占用空間的大小,比如。10000個鍵值對,占用了7w字節。(應用在離線保存embeddings中)
原文鏈接:https://blog.csdn.net/weixin_42327752/article/details/125855403
相關推薦
- 2022-09-08 pandas實現datetime64與unix時間戳互轉_python
- 2022-05-11 C#?中使用Stopwatch計時器實現暫停計時繼續計時功能_C#教程
- 2022-09-10 C#中AutoResetEvent控制線程用法小結_C#教程
- 2022-11-20 Android類加載流程分析_Android
- 2022-09-24 win2003下FTP服務器搭建教程_FTP服務器
- 2022-11-03 Python?文檔解析lxml庫的使用詳解_python
- 2023-06-21 ProtoBuf動態拆分Gradle?Module解析_Android
- 2022-04-28 shell命令執行hive腳本(hive交互)_linux shell
- 最近更新
-
- 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同步修改后的遠程分支