python循环录入列表数据,Python列表通过循环写入,所有先前的值均被覆盖

本文探讨了使用Python创建二维列表时出现的数据覆盖问题,并提供了解决方案。问题源于列表元素的重复引用,导致每次循环更新时都修改了相同的内存地址。通过使用列表推导式创建独立的子列表来避免这一问题。

I'm fairly new to python so I'm sorry if this is a fairly noob question. But I'm writing a 2D list composed of data from .txt file with a for loop (all that code works), but the loop seems to be overwriting all my previously written data each time to passes though even though I'm

This isn't my actually code, but sum up the problem I'm having.

stuff = [[None]*3]*10

for index in range(10):

stuff[index][2]=index

print(stuff)

[[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9]]

Why are all the values being returned as 9, why what do I have to do to get it to return as

[[None, None, 1],[None, None, 2],[None, None, 3],[None, None, 4],[None, None, 5],[None, None, 6],[None, None, 7],[None, None, 8],[None, None, 9]]

解决方案

The reason that this is happening is because of your first line:

stuff = [[None]*3]*10

What this is actually doing is creating only 1 array of [[None]*3] and then referencing it 10 times.

So your array is actually similar to:

[[[None]*3], reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0]

Change your first line to:

stuff = [[None]*3 for i in xrange(10)]

Which will create a unique element at each position within the array.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值