Change List format in Python

Question:

I have an List like down below

[['-6.167665', '106.904251'], ['-6.167665', '106.904251']]

How to make it like this?

[[-6.167665, 106.904251], [-6.167665, 106.904251]]

Any suggestions how to do it?

Asked By: Jessen Jie

||

Answers:

old = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]
new = [list(map(lambda string: float(string), item)) for item in old]
Answered By: Dor-Ron

You want to use float.

original_list = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]
print(original_list)

new_list = [[float(i) for i in inner] for inner in original_list]
print(new_list)
Answered By: iohans

For big arrays numpy would do the trick :

import numpy as np
l1 = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]
l2 = np.array(l1, dtype=np.float32)

output:

[[-6.167665, 106.904251], [-6.167665, 106.904251]]
Answered By: Geovani Benita

You have to convert it to floats

old = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]

new = [list(map(float, i)) for i in old]

new
[[-6.167665, 106.904251], [-6.167665, 106.904251]]
Answered By: Alex

Other answers already have suggested the method of doing it, which is convert to float. The most efficient way to do it is map:

values = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]

float_values = [list(map(float, vals)) for vals in values]

print(float_values)

Gives you:

[[-6.167665, 106.904251], [-6.167665, 106.904251]]
Answered By: yeaske
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.