试图修改一个值时,Python的2D列表中有奇怪的behavor [英] Python 2D list has weird behavor when trying to modify a single value

查看:170
本文介绍了试图修改一个值时,Python的2D列表中有奇怪的behavor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists">Unexpected在列表中的一个Python列表功能

所以我是比较新的Python和我无法用2D解释工作。

So I am relatively new to Python and I am having trouble working with 2D Lists.

下面是我的code:

data = [[None]*5]*5
data[0][0] = 'Cell A1'
print data

和这里(格式为便于阅读)的输出:

and here is the output (formatted for readability):

[['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None]]

为什么每一行获得分配的价值呢?

Why does every row get assigned the value?

推荐答案

这使得有五个引用到同一个列表列表:

This makes a list with five references to the same list:

data = [[None]*5]*5

使用这样的事情,而不是它创建五个单独的列表:

Use something like this instead which creates five separate lists:

>>> data = [[None]*5 for _ in range(5)]

现在它做你所期望的:

>>> data[0][0] = 'Cell A1'
>>> print data
[['Cell A1', None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None]]

这篇关于试图修改一个值时,Python的2D列表中有奇怪的behavor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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