Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: convert 2 dimension list of string to float

I have a 2 dimension list of type string I'm trying to convert it to int. Things I've tried so far:

[[float(i) for i in lst[j] for j in lst]

with a for loop:

for i in range(len(lst)):
    for j in range(len(lst[i])):
         lst[i][j]=float(lst[i][j])
like image 455
user2129468 Avatar asked Feb 05 '26 21:02

user2129468


2 Answers

>>> nums = [['4.58416458379', '3.40522046551', '1.68991195077'], ['3.61503670628', '5.64553650642', '1.39648965337'], ['8.02595866276', '8.42455003038', '7.93340754534']]
>>> [[float(y) for y in x] for x in nums]
[[4.58416458379, 3.40522046551, 1.68991195077], [3.61503670628, 5.64553650642, 1.39648965337], [8.02595866276, 8.42455003038, 7.93340754534]]

I'm not sure what your intention is but since you claim the for loop version didn't work, maybe you want a one dimensional result, in that case:

>>> [float(y) for x in nums for y in x]
[4.58416458379, 3.40522046551, 1.68991195077, 3.61503670628, 5.64553650642, 1.39648965337, 8.02595866276, 8.42455003038, 7.93340754534]
like image 190
jamylak Avatar answered Feb 08 '26 10:02

jamylak


Both of your solutions are close to working. Indeed, the second one should work already, though it can perhaps be improved a little bit.

Here's how I'd update the list comprehension version. The (perhaps dubious) advantage of this version is that it creates a new nested list containing floats, and leaves the original nested list of strings unchanged (so you can use it for something else, if you need to):

new_lst = [[float(string) for string in inner] for inner in lst]

Here's how I'd update your for loop code. Unlike the version using a list comprehension, this code modifies the contents of the original list of lists in place. While your current code should work just fine, the version below is somewhat more "pythonic" in my opinion, since it iterates over the contents of the list, rather than iterating over ranges and indexing the lists. Indexing is only needed for the assignment, and we get the index along with the string using the enumerate built-in function:

for inner in lst:
    for index, string in enumerate(inner):
        inner[index] = float(string)
like image 28
Blckknght Avatar answered Feb 08 '26 11:02

Blckknght