I have a list of strings, it's like:
['25 32 49 50 61 72 78 41\n',
'41 51 69 72 33 81 24 66\n']
I want to convert this list of strings, to a list of lists of ints. So my list would be:
[[25, 32, 49, 50, 61, 72, 78, 41], [41, 51, 69, 72, 33, 81, 24, 66]]
I've been thinking over this for a while, and couldn't find a solution. By the way, the list of strings, which I gave above, is populated using
open("file", "r").readlines()
use split()
to split the string into list, and then use int()
to convert them into integers.
using 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]]
or using list comprehension:
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]]
you can directly create this list from your file also, no need of 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]]
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)
b=[[int(x) for x in i.split()] for i in open("file", "r").readlines()]
尝试此列表理解
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.