亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

自己制作的矩陣函數打印錯誤的項目位置

自己制作的矩陣函數打印錯誤的項目位置

嗶嗶one 2023-03-22 17:12:00
我創建了一個函數,它看起來像是一個矩陣,但是當打印出來時,它沒有打印出矩陣中項目的正確位置。然而,用于顯示當前所在行和列的打印功能確實打印了正確的值,但附加的這些值卻沒有。而不是打?。篬00, 01, 02][10, 11, 12][20, 21, 22]它打?。篬20, 21, 22][20, 21, 22][20, 21, 22]我設法意識到它實際打印的是:[x0, x1, x2][x0, x1, x2][x0, x1, x2]其中 (x = rows - 1) 而不是它應該的當前行。我制作矩陣的腳本是:rows = 3cols = 3matrix = []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(curRow)    printMatrix()def printMatrix():    for item in range(len(matrix)):        print(matrix[item])makeMatrix(rows, cols)
查看完整描述

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)


查看完整回答
反對 回復 2023-03-22
?
繁星淼淼

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 風格為您的函數提供了更好的命名。


查看完整回答
反對 回復 2023-03-22
?
陪伴而非守候

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


查看完整回答
反對 回復 2023-03-22
  • 3 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號