Reputation: 3974
I have a list [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
.
Now I want to convert it into its number equivalent
[[4, 9.012], [12, 24.305], [20, 20.078]]
I am new to python.
Upvotes: 0
Views: 161
Reputation: 24758
>>> l = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
>>> l1 = [ [ float(i[0]), float(i[1]) ] for i in l ]
OR
>>> 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]]
Upvotes: 0
Reputation: 5401
lst = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
map(lambda x: [int(x[0]), float(x[1])], lst)
Upvotes: 0
Reputation: 142136
You can use:
from ast import literal_eval
newlist = [[literal_eval(el) for el in item] for item in mylist]
This way the type will be determined by the type required to hold that number.
Upvotes: 3
Reputation: 198324
If you always have pairs of integer and float,
[[int(x), float(y)] for [x, y] in mylist]
Otherwise, for more generality at the expense of type correctness,
[[float(x) for x in s] for s in mylist]
For more type correctness at the expense of clarity,
def number(x):
try:
return int(x)
except:
return float(x)
[[number(x) for x in s] for s in mylist]
Upvotes: 1