網站首頁 編程語言 正文
對列表深拷貝就是無論怎樣改動新列表(單維or多維),原列表都不變。
而下面的淺拷貝,對于多維列表,只是第一維深拷貝了(嵌套的List保存的是地址,復制過去的時候是把地址復制過去了),所以說其內層的list元素改變了,原列表也會變。
一、淺拷貝(均是只對第一層進行深拷貝)
1. for循環依次賦值
old = [1, [1, 2, 3], 3] new = [] for i in range(len(old)): ? ? new.append(old[i]) new[0] = 3 new[1][0] = 3 print(old) print(new) ''' [1, [3, 2, 3], 3] [3, [3, 2, 3], 3] '''
2. 使用copy()函數
old = [1,[1,2,3],3] new = old.copy() new[0] = 3 new[1][0] =3 print(old) print(new)
輸出:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
3. 使用列表生成式
old = [1,[1,2,3],3] new = [i for i in old] ? new[0] = 3 new[1][0] = 3 print(old) print(new)
輸出:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
4. 使用索引 [:]
old = [1,[1,2,3],3] new = old[:] ? new[0] = 3 new[1][0] = 3 print(old) print(new)
輸出:
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
淺拷貝對于單層列表就是深拷貝,如:
old = [1,2,3] new = old[:] new[0] = 666 print(old) print(new) """ [1, 2, 3] [666, 2, 3] """
二、深拷貝
使用用deepcopy()方法,才是真正的復制了一個全新的和原列表無關的:
import copy old = [1,[1,2,3],3] new = copy.deepcopy(old) ? new[0] = 3 new[1][0] = 3 """ [1, [1, 2, 3], 3] [3, [3, 2, 3], 3] """
原文鏈接:https://blog.csdn.net/weixin_43646592/article/details/119744273
相關推薦
- 2022-01-20 空值判斷運算符 ? ?
- 2023-06-05 Go實現共享庫的方法_Golang
- 2022-07-16 typescript封裝websocket,監測心跳,斷開重連
- 2022-12-09 C++印刷模板使用方法詳解_C 語言
- 2023-02-01 python?multiply()與dot使用示例講解_python
- 2022-04-28 python實現線性回歸的示例代碼_python
- 2022-04-12 python入門之Scrapy?shell的使用_python
- 2023-04-02 淺談Android開發Webview的Loading使用效果_Android
- 最近更新
-
- 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同步修改后的遠程分支