简体   繁体   English

如何将带有数字字符串的列表转换为整数列表?

[英]How to convert a list with a string of numbers into a list of intergers?

I have a list of lists and inside the lists are strings of multiple numbers. 我有一个列表列表,列表中是多个数字的字符串。 For example, [['34,53,53,21'], ['43,65,12,53'], ['54,23,31,34']] 例如, [['34,53,53,21'], ['43,65,12,53'], ['54,23,31,34']]

and I want the result to look like: [[34,53,53,21], [43,65,12,53], [54,23,31,34]] with all integers inside. 我希望结果看起来像: [[34,53,53,21], [43,65,12,53], [54,23,31,34]] ,里面有所有整数。 I've tried numerous code, but keep getting different error messages. 我尝试了许多代码,但是不断收到不同的错误消息。

Also, what about if some of the interior numbers were a float? 另外,如果某些内部数字是浮点数呢? Such as: [['34,53.09,53.56,21.98'], ['43,65.67,12.45,53.45'], ['54,23.34,31.23,34.76']] 如: [['34,53.09,53.56,21.98'], ['43,65.67,12.45,53.45'], ['54,23.34,31.23,34.76']]

>>> L = [['34,53,53,21'], ['43,65,12,53'], ['54,23,31,34']]
>>> [[int(y) for y in x[0].split(',')] for x in L]
[[34, 53, 53, 21], [43, 65, 12, 53], [54, 23, 31, 34]]

For floats: 对于花车:

>>> L = [['34,53.09,53.56,21.98'], ['43,65.67,12.45,53.45'], ['54,23.34,31.23,34.76']]
>>> [[float(y) for y in x[0].split(',')] for x in L]
[[34.0, 53.09, 53.56, 21.98], [43.0, 65.67, 12.45, 53.45], [54.0, 23.34, 31.23, 34.76]]
[[int(y) for y in x[0].split(',')] for x in lst]

On python 2.x, you could use: 在python 2.x上,您可以使用:

[map(int,x[0].split(',')) for x in lst]

And in some ways, having inner list of the strings is inconvenient. 而且在某些方面,内部字符串列表不方便。 You could use chain to remove them: 您可以使用chain来删除它们:

from itertools import chain
[[int(y) for y in x.split(',')] for x in chain.from_iterable(lst)]

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

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