如何将列表(矩阵)拆分成其他列表?

时间:2014-10-29 15:32:51

标签: python list matrix arraylist split

我不知道如何将10x10的矩阵转换为5x5的四个矩阵,例如:

[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], # matrix 10x10
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]

我需要转换成这个:

[[10, 11, 12, 13, 14] # 4 like this with the other numbers too
 [20, 21, 22, 23, 24] 
 [30, 31, 32, 33, 34]
 [40, 41, 42, 43, 44]
 [50, 51, 52, 53, 54]]

1 个答案:

答案 0 :(得分:2)

您可以使用slicinglist comprehension

>>> matrix = \
... [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
...  [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
...  [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
...  [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
...  [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
...  [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
...  [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
...  [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
...  [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
...  [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]
>>> from pprint import pprint
>>> pprint([x[:5] for x in matrix[:5]])
[[10, 11, 12, 13, 14],
 [20, 21, 22, 23, 24],
 [30, 31, 32, 33, 34],
 [40, 41, 42, 43, 44],
 [50, 51, 52, 53, 54]]
>>>

sequence[:5]获取sequence中的前五项。因此,matrix[:5]获取matrix中的前五个子列表,x[:5]获取每个子列表中的前五个项目。 pprint.pprint仅用于格式化输出。