3 回答

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
您將覆蓋您的curRow3 次,然后最后一個(gè)值將是該變量的值。如果你不想要這種行為,你需要像這樣克隆你的列表:
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貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
由于嵌套 for ,您正在覆蓋行。這就是為什么總是采用最新的數(shù)字。你可以這樣解決這個(gè)問(wèn)題:
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 風(fēng)格為您的函數(shù)提供了更好的命名。

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您將行替換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']
這是在.下測(cè)試的Python 2.7。
Python 3.5在我得到相同結(jié)果的情況下實(shí)際測(cè)試您的原始代碼:
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']
添加回答
舉報(bào)