简体   繁体   English

如何将字符串列表拆分为整数列表?

[英]How can I split this list of strings to list of lists of ints?

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. 使用split()将字符串拆分为列表,然后使用int()将其转换为整数。

using map() : 使用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() : 您也可以直接从文件中创建此列表,而无需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()]

尝试此列表理解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM