Assign value to an individual cell in a two dimensional python array
假设我在python中有以下空的二维数组:
1 | q = [[None]*5]*4 |
我想将EDOCX1的值〔0〕分配给
1 | q[0][0] = 5 |
但是,这会产生:
1 2 3 4 | [[5, None, None, None, None], [5, None, None, None, None], [5, None, None, None, None], [5, None, None, None, None]] |
每个数组的第一个元素被初始化为
这不符合你的期望。
1 | q = [[None]*5]*4 |
它多次重复使用
使用值为
使用值为
1 | q = [ [ None for i in range(5) ] for j in range(4) ] |
可能更多的是你想要的。
这样可以显式地避免重用列表对象。
80%的时候,字典是你真正想要的。
1 2 | q = {} q[0,0]= 5 |
也可以。您不需要从一个预先定义的
在Python2.7及更高版本中,您可以这样做。
1 | q = { (i,j):0 for i in range(5) for j in range(4) } |
这将构建一个由两个元组索引的网格。
1 | {(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每次重新生成该列表:
1 | [ [None] * 5 for i1 in range(4) ] |
在这种情况下,我使用的是列表理解。
1 2 3 4 5 6 7 | q = [[None]*5]*4 print(q) q[1][1]=4 print(q) q = [ [ None for i in range(5) ] for j in range(4) ] q[1][1]=4 print(q) |
结果:
1 2 3 | [[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]] [[None, 4, None, None, None], [None, 4, None, None, None], [None, 4, None, None, None], [None, 4, None, None, None]] [[None, None, None, None, None], [None, 4, None, None, None], [None, None, None, None, None], [None, None, None, None, None]] |
答案很简单,永远不要用
1 | q = [[None]*5]*4 |
当你做作业的时候
宁愿用
1 | q = { (i,j):0 for i in range(5) for j in range(4) } |
那么,
1 | print(q) |
问题2的答案:使用numpy是一个选项。请参见以下代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import numpy as np # creating 2D array with nans num_of_rows = 5 num_of_cols = 3 a = np.full((num_of_rows, num_of_cols), np.nan) #for zero vals: a = np.zeros((num_of_rows, num_of_cols)) # placing number 5 in row 3, col 1 value = [5] position_row = 3 position_col = 1 # the put command below flattens the 2D array position = [int(num_of_cols * position_row + position_col)] np.put(a, position, value) |
结果:
1 2 3 4 5 | [[ nan nan nan] [ nan nan nan] [ nan nan nan] [ nan 5. nan] [ nan nan nan]] |
如果您想使用列表而不是其他人建议的词典,您可以使用:
1 | q[0] = [5,None,None,None,None] |
Why is Python initializing the first value of every array and not just the first one?
因为它们是相同的数组,被多次引用。
Is there a better way to accomplish what I'm trying to do?
创建结构,使外部数组引用单独的内部数组,而不是重用一个。其他答案提供了这样做的方法。