0

我有一个清单[['4', '9.012'], ['12', '24.305'], ['20', '20.078']]

现在我想把它转换成它的等价数字

[[4, 9.012], [12, 24.305], [20, 20.078]] 

我是 python 新手。

4

4 回答 4

3

您可以使用:

from ast import literal_eval
newlist = [[literal_eval(el) for el in item] for item in mylist]

这样,类型将由保存该数字所需的类型确定。

于 2013-09-08T18:16:32.790 回答
1

如果你总是有成对的整数和浮点数,

[[int(x), float(y)] for [x, y] in mylist]

否则,为了更通用,以牺牲类型正确性为代价,

[[float(x) for x in s] for s in mylist]

为了以清晰度为代价获得更多的类型正确性,

def number(x): 
  try: 
    return int(x) 
  except: 
    return float(x)
[[number(x) for x in s] for s in mylist]
于 2013-09-08T18:01:11.727 回答
0
>>> l = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
>>> l1 = [ [ float(i[0]), float(i[1]) ]    for i in l ]

或者

>>> l
[['4', '9.012'], ['12', '24.305'], ['20', '20.078']]

>>> def f(arg):
...     return [float(arg[0]), float(arg[1])]

>>> map(f,l)
[[4.0, 9.012], [12.0, 24.305], [20.0, 20.078]]
于 2013-09-08T19:51:00.570 回答
0
lst = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
map(lambda x: [int(x[0]), float(x[1])], lst)
于 2013-09-08T19:03:52.650 回答