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])
>>> 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]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With