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

时间:2013-04-22 05:18:46

标签: python string list

我有一个列表列表,列表中有多个字符串。例如, [['34,53,53,21'], ['43,65,12,53'], ['54,23,31,34']]

我希望结果如下: [[34,53,53,21], [43,65,12,53], [54,23,31,34]] 内部所有整数。我尝试过很多代码,但不断收到错误消息。

另外,如果一些内部数字是浮动的呢?例如: [['34,53.09,53.56,21.98'], ['43,65.67,12.45,53.45'], ['54,23.34,31.23,34.76']]

2 个答案:

答案 0 :(得分:3)

>>> 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]]

对于花车:

>>> 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]]

答案 1 :(得分:3)

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

在python 2.x上,您可以使用:

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

在某些方面,拥有字符串的内部列表是不方便的。您可以使用chain删除它们:

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