pokrate
pokrate

Reputation: 3974

Converting string list to number equivalent

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

Answers (4)

Ankur Agarwal
Ankur Agarwal

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

lovesh
lovesh

Reputation: 5401

lst = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
map(lambda x: [int(x[0]), float(x[1])], lst)

Upvotes: 0

Jon Clements
Jon Clements

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

Amadan
Amadan

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

Related Questions