Python錯誤程式碼分析:莫名的[TypeError: 'int' object is not iterable]
阿新 • • 發佈:2019-02-20
一專案執行時出現如下錯誤提示:
TypeError: 'int' object is not iterable
錯誤程式碼最終定位於自定義函式 modify_table1() 第9行:
cells[j].text = rec_list[i][j]
將此行程式碼修改如下,執行正常:
if isinstance(rec_list[i][j], int):
field_value = str(rec_list[i][j])
else:
field_value = rec_list[i][j]
cells[j].text = field_value
錯誤原因:資料型別不匹配。
錯誤程式碼(片斷)如下:
def modify_table1(docx, rec_list, prime_list): # rec_list: [(name, aqi, grade, prime),] tb = docx.tables[0] prime_list = get_prime_list(rec_list) rec_count = len(rec_list) for i in range(1, rec_count): cells = tb.row_cells(i) for j in range(3): cells[j].text = rec_list[i][j] cell_para1 = cells[j].paragraphs[0] cell_para1.alignment = WD_ALIGN_PARAGRAPH.CENTER cells[3].text = prime_list[i] cell_para1 = cells[3].paragraphs[0] cell_para1.alignment = WD_ALIGN_PARAGRAPH.CENTER return
呼叫函式:
def create_report(filename, rec_list):
path = "byc.docx"
docx = Document(path)
prime_list = get_prime_list(rec_list) # chinese prime
modify_para1(docx, rec_list, prime_list[0])
modify_table1(docx, rec_list, prime_list)
docx.save(filename)
return