ManuelVillamil
ManuelVillamil

Reputation: 87

Converting to float a list of lists containing strings

I have this List of lists containing string values:

List = [['138.314038', '-35.451642'],
['138.313946', '-35.45212'],
['138.313395', '-35.45291'],
['138.312425', '-35.453978'],
['138.311697', '-35.454879'],
['138.311042', '-35.45569'],
['138.310407', '-35.45647'],
['138.315603', '-35.44981'],
['138.315178', '-35.450241'],
['138.314603', '-35.450948'],
['138.314038', '-35.45164']]

I am trying to transform each string value in the list of lists into a float value.

I was trying:

results = [float(i) for i in List]

But I am only indexing the lists and not the values inside. How can I do it using a similar approach and keeping the same structure of the variable List.

Upvotes: 1

Views: 982

Answers (6)

W_water_m
W_water_m

Reputation: 11

You could use map to achieve it.

floats = [ list(map(float, i)) for i in List ]

Upvotes: 1

qaiser
qaiser

Reputation: 2868

#you can use map function as well
results = [list(map(float,x)) for x in List]

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71570

Maybe ugly using two list maps:

print(list(map(lambda x: list(map(float,x)), List)))

Output:

[[138.314038, -35.451642], [138.313946, -35.45212], [138.313395, -35.45291], [138.312425, -35.453978], [138.311697, -35.454879], [138.311042, -35.45569], [138.310407, -35.45647], [138.315603, -35.44981], [138.315178, -35.450241], [138.314603, -35.450948], [138.314038, -35.45164]]

Print it better:

pprint.pprint(list(map(lambda x: list(map(float,x)), List)))

Output:

[[138.314038, -35.451642],
 [138.313946, -35.45212],
 [138.313395, -35.45291],
 [138.312425, -35.453978],
 [138.311697, -35.454879],
 [138.311042, -35.45569],
 [138.310407, -35.45647],
 [138.315603, -35.44981],
 [138.315178, -35.450241],
 [138.314603, -35.450948],
 [138.314038, -35.45164]]

Upvotes: 2

recnac
recnac

Reputation: 3744

you can expand the list, like this:

results = [list(map(float, l)) for l in List]

Upvotes: 1

BENY
BENY

Reputation: 323226

I am using numpy convert it

np.array(List).astype(float).tolist()
Out[185]: 
[[138.314038, -35.451642],
 [138.313946, -35.45212],
 [138.313395, -35.45291],
 [138.312425, -35.453978],
 [138.311697, -35.454879],
 [138.311042, -35.45569],
 [138.310407, -35.45647],
 [138.315603, -35.44981],
 [138.315178, -35.450241],
 [138.314603, -35.450948],
 [138.314038, -35.45164]]

Upvotes: 4

Netwave
Netwave

Reputation: 42678

You have list, so use a double comprehension:

results = [[float(i) for i in e] for e in List]

Upvotes: 4

Related Questions