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

arrays - Why is python printing weird results while using the nested loop here?

I was given an array of strings and I want to split each of the individual strings into separate characters and store them in a separate 2-D array. I wrote the following code:-

# The given array
grid = ['1112', '1912', '1892', '1234']

# Creating a new 2D array
mat = [[None]*len(grid)]*len(grid)
for i in range(0,len(grid)):
    for j in range(0,len(grid)):
        mat[i][j] = grid[i][j]
print(mat)

But doing this gives weird values in my two-dimensional array, mat. Each of the row of the 2D array mat gets printed as ['1','2','3','4'] but this should be the value of the last row only.

I shall be thankful if someone could answer my query.


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

1 Reply

0 votes
by (71.8m points)
mat = [[None]*len(grid)]*len(grid)

This statement is creating a relational 2D array (matrix), so whenever you are updating a line, it will update all the other lines.

You should be using this to create an empty 2D array:

mat = [[None for i in len(grid)] for j in range(len(grid))]

As @marc commented, you can also pass one list comprehension as width = height here

mat = [[None]*len(grid) for _ in range(len(grid))]

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

...