Python列表通过循环写入,所有先前的值都将被覆盖 [英] Python list writing through loop, all previous values being overwritten

查看:301
本文介绍了Python列表通过循环写入,所有先前的值都将被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python还是很陌生,所以如果这是一个菜鸟问题,我感到抱歉.但是我正在写一个由.txt文件中的数据组成的2D列表,并带有for循环(所有代码都起作用),但是即使我是

这不是我的实际代码,但总结一下我遇到的问题.

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]]

为什么所有值都将返回为9,为什么要做什么才能使其返回为

[[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]]

解决方案

发生这种情况的原因是由于您的第一行:

stuff = [[None]*3]*10

这实际上是在仅创建[[None]*3]1数组,然后引用它10次.

所以您的数组实际上类似于:

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

将第一行更改为:

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

这将在数组中的每个位置创建一个唯一元素.

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.

这篇关于Python列表通过循环写入,所有先前的值都将被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆