我有一个字符串列表,就像:
['25 32 49 50 61 72 78 41\n',
'41 51 69 72 33 81 24 66\n']
我想将此字符串列表转换为整数列表列表。所以我的清单是:
[[25, 32, 49, 50, 61, 72, 78, 41], [41, 51, 69, 72, 33, 81, 24, 66]]
我一直在考虑这个问题,但找不到解决方案。顺便说一句,我上面给出的字符串列表是使用
open("file", "r").readlines()
用于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]]
b=[[int(x) for x in i.split()] for i in open("file", "r").readlines()]
试试这个列表理解
x = ['25 32 49 50 61 72 78 41\n', '41 51 69 72 33 81 24 66\n']
map(lambda elem:map(int, elem.split()), x)