您应该首先围绕空格拆分以获取行,然后迭代这些行以获取单元格:
>>> rows = "2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9".split(' ')
>>> rows
['2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9']
>>> [row.split(',') for row in rows]
[['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9']]
您还可以将这些单元格转换为整数:
>>> [[int(cell) for cell in row.split(',')] for row in rows]
[[2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9]]
还是让
numpy
为您进行转换:
>>> import numpy as np
>>> np.array([row.split(',') for row in rows], np.int)
array([[2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 4, 5, 6, 7, 8, 9]])