matrix = [ [1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 4, 3], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ]
我想每一行只保留5个元素,超出的部分不要,结果是这样
matrix = [ [1, 2, 3, 4, 5], [9, 8, 7, 6, 5], [0, 1, 2, 3, 4,] ]
我的写法是下面这样,但报错:
[[list[i] for list in matrix[j] for i in [0, 1, 2]] for j in [0, 1, 2]]
你要不先写 for
循环版本,再改成 列表推导式
matrix = [[i for i in row[:5]] for row in matrix]