1

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

and I want the result to look like: [[34,53,53,21], [43,65,12,53], [54,23,31,34]] with all integers inside. 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']]

4

2 回答 2

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)]
于 2013-04-22T05:20:01.427 回答
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]]
于 2013-04-22T05:19:38.007 回答