The list of list is modified unexpected, python
2024-08-23 12:09:40
Be careful!
The list of list is modified unexpected, python
# code patch A:
list = [1,2,3,4,5,6,7]
print('list A :', list)
for i in list:
temp = i
if i > 5:
temp = i + 10000
print('list A\':', list)
# code patch B:
list = [[1],[2],[3],[4],[5],[6],[7]]
new_list = []
print('\nlist B : ',list)
for i in list:
temp = i # will this allocate a new RAM space for var 'temp'?
if i[0] > 5:
temp[0] = i[0] + 1000
new_list.append(temp)
print('list B\': ', list, end='')
print(' <-- you can see the list is changed, which is not i want.')
print('new_list:', new_list)
# code patch C:
list = [[1],[2],[3],[4],[5],[6],[7]]
new_list = []
print('\nlist C : ',list)
for i in list:
temp = [''] # only this line is MODIFIED than code patch B.
temp[0] = i[0]
if i[0] > 5:
temp[0] = i[0] + 1000
new_list.append(temp)
print('list C\': ', list, end='')
print(' <-- you can see the list is NOT changed.')
print('new_list:', new_list)
'''
Output:
---
list A : [1, 2, 3, 4, 5, 6, 7]
list A': [1, 2, 3, 4, 5, 6, 7]
list B : [[1], [2], [3], [4], [5], [6], [7]]
list B': [[1], [2], [3], [4], [5], [1006], [1007]] <-- you can see the list is changed. which is not i want.
new_list: [[1], [2], [3], [4], [5], [1006], [1007]]
list C : [[1], [2], [3], [4], [5], [6], [7]]
list C': [[1], [2], [3], [4], [5], [6], [7]] <-- you can see the list is NOT changed.
new_list: [[1], [2], [3], [4], [5], [1006], [1007]]
Question:
why list B' is modified in the for loop?
'''
最新文章
- [转]MySQL: Starting MySQL….. ERROR! The server quit without updating PID file
- hdu3847Trash Removal(凸包)
- 小波说雨燕 第三季 构建 swift UI 之 UI组件集-视图集(三)Activity Indicators视图 学习笔记
- python数字图像处理(4):图像数据类型及颜色空间转换
- windows常见已知熟悉操作命令
- ROS主题发布订阅
- WCF入门教程一[什么是WCF]--转载只为学习收藏
- 判断是否是IP地址
- LeetCode_Scramble String
- 解决Xcode7之后发送网络请求http格式不支持报错问题
- MySQL PHP 语法
- 我的第一个SpringProject——HelloWorld
- sklearn的kmeans测试
- ajax请求,函数外无法获取请求的数据问题解决
- Java生成短链接
- 《Linux 性能及调优指南》写在后面的话
- artTemplate子模板include
- 关于Oracle与MySQL的使用总结
- Linux(CentOS)系统下搭建svn服务器
- zoj-3410-Layton&#39;s Escape