您可以使用生成器函数:def solve(f, n, m):
lis = []
for line in f:
if len(lis) > m:
yield lis[:m]
lis = lis[m:]
lis.extend(map(int, line.split()))
for i in xrange(0, len(lis), m):
yield lis[i:i+m]
with open('abc1') as f:
n, m = map(int, next(f).split())
# Now you can either load the whole array at once using the list() call,
# or use a simple iteration to get one row at a time.
matrix = list(solve(f, n, m))
print matrix
输出:
^{pr2}$
另一种方法是获取文件中所有项的平坦迭代器,然后将该迭代器拆分为大小相等的块。在from itertools import chain, islice
with open('abc1') as f:
n, m = map(int, next(f).split())
data = chain.from_iterable(map(int, line.split()) for line in f)
matrix = [list(islice(data, m)) for i in xrange(n)]
print matrix
#[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
相关: