在 python 中定义一个二维列表

define a 2d list in python

rows = 7  
cols = 6  
mat = []  
for i in range(cols):
    col = []  
    for j in range(rows):
        col.append(0)  
    mat.append(col) 

for i in range(cols):  
    for j in range(rows):
        print(mat[j])
    print('\n')

为什么会出现 //IndexError: list index out of range// 错误?

因为第二个for循环中有print(mat[j]),所以应该这样写:

 print(mat[i][j]), end = " ")
print()

你可以使用

rows = 7  
cols = 6  
mat = []  
for i in range(cols):
    col = []  
    for j in range(rows):
        col.append(0)  
    mat.append(col) 

for i in range(cols):  
    for j in range(rows):
        print(mat[i][j], end = " ")
    print('\n')

在这里您将一一打印每个值。 或者另一种方法是一次打印整行:

rows = 7  
cols = 6  
mat = []  
for i in range(cols):
    col = []  
    for j in range(rows):
        col.append(0)  
    mat.append(col) 

for i in range(cols):  
    print(mat[i])
print('\n')

IndexError 是因为,您正在尝试访问不存在的元素。