用于split()
将字符串拆分为列表,然后用于int()
将它们转换为整数。
使用map()
:
In [10]: lis=['25 32 49 50 61 72 78 41\n',
....: '41 51 69 72 33 81 24 66\n']
In [11]: [map(int,x.split()) for x in lis]
Out[11]: [[25, 32, 49, 50, 61, 72, 78, 41], [41, 51, 69, 72, 33, 81, 24, 66]]
或使用列表理解:
In [14]: [[int(y) for y in x.split()] for x in lis]
Out[14]: [[25, 32, 49, 50, 61, 72, 78, 41], [41, 51, 69, 72, 33, 81, 24, 66]]
您也可以直接从您的文件中创建此列表,无需readlines()
:
with open("file") as f:
lis=[map(int,line.split()) for line in f]
print lis
...
[[25, 32, 49, 50, 61, 72, 78, 41], [41, 51, 69, 72, 33, 81, 24, 66]]