Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

list - Initializing 2D array in Python

I have a problem with initialzing a 2D array in python. I want a 6x6 array, I did

arr = [[None]*6]*6

But when I do:

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

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?

I figured

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)

works, but it seems long to just initialize an empty 6x6 array, what if I want a 10000x10000 array, it will be very inefficient?

UPDATE

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 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@Cameron is correct in suggesting that you use NumPy to deal with arrays of numerical data. And for the second part of your question, ~Niklas B. is spot on with his suggestion to use defaultdict.

What hasn't been covered is why [[None]*6]*6 behaves strangely.

The answer is that [None]*6 creates a list with six Nones in it (like you expect), but [list]*6 does not make six independent copies of list - it makes six copies of a reference to the same list.

Idiomatic Python has a section that may explain this better: "Other languages have variables - Python has names".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...