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
692 views
in Technique[技术] by (71.8m points)

list - Creating a 2d matrix in python

I create a 6x5 2d array, initially with just None in each cell. I then read a file and replace the Nones with data as I read them. I create the empty array first because the data is in an undefined order in the file I'm reading. My first attempt I did this:

x = [[None]*5]*6

which resulted in some weird errors that I now understand is because the * operator on lists may create references instead of copies.

Is there an easy one liner to create this empty array? I could just do some for loops and build it up, but that seems needlessly verbose for python.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using nested comprehension lists :

x = [[None for _ in range(5)] for _ in range(6)]

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

...