在Python中初始化2D数组 [英] Initializing 2D array in Python
问题描述
我在python中初始化2D数组时遇到问题.我想要一个6x6的阵列,我做到了
I have a problem with initialzing a 2D array in python. I want a 6x6 array, I did
arr = [[None]*6]*6
但是当我这样做时:
>>> arr[1][2]=10
>>> arr
[[None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None]]
注意,我只设置了1个项目,并且在所有行上都将其复制"了.怎么了?我认为它与引用相同的列表有关,但是我该如何解决呢?
Notice I just set 1 item, and its "replicated" on all rows. Whats wrong? I think it has to do with its referencing the same list, but how do I fix this?
我想通了
for key, _ in algos.items():
algoData[key] = []
for i in range(0,6):
algoData[key].append([])
for j in range(0,6):
algoData[key][i].append(None)
可以工作,但是只是初始化一个空的6x6数组似乎很长,如果我想要10000x10000数组怎么办,效率会很低?
works, but it seems long to just initialize an empty 6x6 array, what if I want a 10000x10000 array, it will be very inefficient?
更新
我还可以初始化2D数组的字典吗?我有一本类似的字典:
Can I also initialize a dictionary of 2D arrays? I have a dictionary like:
algos = { "FIFO": ..., "LRU": ..., "Random": ... }
我想初始化一个字典,如下所示:
I want to initialize a dictionary like below:
algoData = { "FIFO": 2D arr, "LRU": 2D arr, "Random": 2D arr }
推荐答案
使用列表推导,您可以说:
Using list comprehensions, you can say:
arr = [[None for x in range(6)] for y in range(6)]
然后,您将按预期的方式运行arr[1][2] = 10
.但是,这不是很正常的事情.您打算将嵌套列表用于什么?可能有更好的方法.例如,使用numpy包使处理数组变得更加容易.
Then you will have arr[1][2] = 10
working as expected. This is not a very normal thing to do, however. What are you going to use the nested lists for? There may be a better way. For example, working with arrays is made much easier with the numpy package.
这篇关于在Python中初始化2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!