python二维数组创建赋值问题:更改单个值却更改了所有项的值

python 复制代码
test_list = []
dic1 = {}
test_list = [dic1 for _ in range(3)]
ll = [1, 2, 3]

for i in range(3):
    test_list[i]['value'] = ll[i]

print(test_list)

运行结果:每次赋值都更改了所有项

原因:python的二位数据创建方式就是这样,官方文档中有描述What has happened is that [[]] is a one-element list containing an empty list,

so all three elements of [[]] * 3 are references to this single empty list.

Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

python 复制代码
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

那么,将上述代码修改为:

python 复制代码
test_list = []
test_list = [{} for _ in range(3)]
ll = [1, 2, 3]

for i in range(3):
    test_list[i]['value'] = ll[i]

print(test_list)

结果正确:

相关推荐
云泽野3 小时前
【Java|集合类】list遍历的6种方式
java·python·list
IMPYLH5 小时前
Python 的内置函数 reversed
笔记·python
小赖同学啊7 小时前
物联网数据安全区块链服务
开发语言·python·区块链
码荼7 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud
小陈phd8 小时前
李宏毅机器学习笔记——梯度下降法
人工智能·python·机器学习
kk爱闹8 小时前
【挑战14天学完python和pytorch】- day01
android·pytorch·python
Blossom.1188 小时前
机器学习在智能建筑中的应用:能源管理与环境优化
人工智能·python·深度学习·神经网络·机器学习·机器人·sklearn
亚力山大抵8 小时前
实验六-使用PyMySQL数据存储的Flask登录系统-实验七-集成Flask-SocketIO的实时通信系统
后端·python·flask
showyoui8 小时前
Python 闭包(Closure)实战总结
开发语言·python
amazinging9 小时前
北京-4年功能测试2年空窗-报培训班学测开-第四十一天
python·学习·appium