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?
Answers:
old = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]
new = [list(map(lambda string: float(string), item)) for item in old]
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)
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]]
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]]
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]]
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?
old = [['-6.167665', '106.904251'], ['-6.167665', '106.904251']]
new = [list(map(lambda string: float(string), item)) for item in old]
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)
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]]
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]]
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]]