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

Categories

0 votes
283 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...