为二维python数组中的单个单元格赋值 [英] Assign value to an individual cell in a two dimensional python array
问题描述
假设我在 Python 中有以下空二维数组:
Let's say I have the following empty two dimensional array in Python:
q = [[None]*5]*4
我想给q
第一列的第一行赋值5
.本能地,我做了以下事情:
I want to assign a value of 5
to the first row in the first column of q
. Instinctively, I do the following:
q[0][0] = 5
然而,这会产生:
[[5, None, None, None, None],
[5, None, None, None, None],
[5, None, None, None, None],
[5, None, None, None, None]]
每个数组的第一个元素被初始化为5
,我认为只有第一个数组的第一个元素会得到更新.我有两个问题:
The first element of every array is being initialized to 5
, where I thought only the first element of the first array would get the update. I have two questions:
- 为什么 Python 初始化每个数组的第一个值而不是第一个?
- 有没有更好的方法来完成我想要做的事情?
推荐答案
这不符合您的期望.
q = [[None]*5]*4
它多次重用 list
对象.正如您在对一个单元格进行更改时所看到的,该单元格位于重复使用的列表对象中.
It reuses list
objects multiple times. As you can see when you made a change to one cell, which was in a reused list object.
值为 [None]
的单个列表被使用了五次.
A single list with a value of [None]
is used five times.
值为 [[None]*5]
的单个列表使用了四次.
A single list with a value of [[None]*5]
is used four times.
q = [ [ None for i in range(5) ] for j in range(4) ]
可能更符合您的要求.
这明确避免了重复使用列表对象.
This explicitly avoids reusing a list object.
80% 的情况下,您真正想要的是字典.
80% of the time, a dictionary is what you really wanted.
q = {}
q[0,0]= 5
也能用.您不会从 None
值的预定义网格开始.但一开始就很少需要它们.
Will also work. You don't start with a pre-defined grid of None
values. But it's rare to need them in the first place.
在 Python 2.7 及更高版本中,您可以这样做.
In Python 2.7 and higher, you can do this.
q = { (i,j):0 for i in range(5) for j in range(4) }
这将构建一个由 2 元组索引的网格.
That will build a grid indexed by 2-tuples.
{(0, 1): 0, (1, 2): 0, (3, 2): 0, (0, 0): 0, (3, 3): 0, (3, 0): 0, (3, 1): 0, (2, 1): 0, (0, 2): 0, (2, 0): 0, (1, 3): 0, (2, 3): 0, (4, 3): 0, (2, 2): 0, (1, 0): 0, (4, 2): 0, (0, 3): 0, (4, 1): 0, (1, 1): 0, (4, 0): 0}
这篇关于为二维python数组中的单个单元格赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!