Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing all strings except one in a list of lists to a float

I have a list of lists:

LofL = [["string", "number", "number", "number"], ["string", "number", "number", "number"], ...]

and im trying to turn the numbers within the list of lists to floats instead of strings. Each list of list is not equal in length. So far I have:

for sublist in LofL:
sublist[1:] = float(sublist[1:])

but I’m getting the error float argument must be a string or real number not a list. This works for single numbers if I do sublist[1] = float(sublist[1]) but I’m unsure of how to include all numbers in each list of lists without the [1:] indexing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for sublist in LofL:
    for i in range(1, len(sublist)):
        sublist[i]=float(sublist[i])

Explanation:
Your initial code sublist[1:]=float(sublist[1:] will not work as sublist[1:] is a list and you cannot turn list to a float.

So the for i in range(1, len(sublist) will iterate through each element in your sublist
then with each iteration we will convert sublist[i]=float(sublist[i] into float. Because you specified that the first item of sublist does not need to change hence we are starting our loop from 1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading