3 回答
TA贡献1858条经验 获得超8个赞
您将覆盖您的curRow3 次,然后最后一个值将是该变量的值。如果你不想要这种行为,你需要像这样克隆你的列表:
rows = 3
cols = 3
matrix = []
def makeMatrix(rows, cols):
curRow = []
for row in range(rows):
curRow.clear()
print("Row: ", row)
for col in range(cols):
print("Col: ", col)
toAppend = str(row) + str(col)
curRow.append(toAppend)
matrix.append(list.copy(curRow)) #Make a clone
printMatrix()
def printMatrix():
for item in range(len(matrix)):
print(matrix[item])
makeMatrix(rows, cols)
TA贡献1775条经验 获得超11个赞
由于嵌套 for ,您正在覆盖行。这就是为什么总是采用最新的数字。你可以这样解决这个问题:
rows = 3
cols = 3
matrix = []
def make_matrix(rows, cols):
for row in range(rows):
curRow = []
print("Row: ", row)
for col in range(cols):
print("Col: ", col)
toAppend = str(row) + str(col)
curRow.append(toAppend)
matrix.append(curRow)
print_matrix()
def print_matrix():
for item in range(len(matrix)):
print(matrix[item])
make_matrix(rows, cols)
我希望这有帮助。此外,我按照 PEP8 风格为您的函数提供了更好的命名。
TA贡献1757条经验 获得超8个赞
如果您将行替换curRow.clear()为curRow = []您将获得所需的输出,如下所示:
>>>
('Row: ', 0)
('Col: ', 0)
('Col: ', 1)
('Col: ', 2)
('Row: ', 1)
('Col: ', 0)
('Col: ', 1)
('Col: ', 2)
('Row: ', 2)
('Col: ', 0)
('Col: ', 1)
('Col: ', 2)
['00', '01', '02']
['10', '11', '12']
['20', '21', '22']
这是在.下测试的Python 2.7。
Python 3.5在我得到相同结果的情况下实际测试您的原始代码:
In [21]: makeMatrix(rows, cols)
Row: 0
Col: 0
Col: 1
Col: 2
Row: 1
Col: 0
Col: 1
Col: 2
Row: 2
Col: 0
Col: 1
Col: 2
['00', '01', '02']
['10', '11', '12']
['20', '21', '22']
添加回答
举报