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

List of lists: looping to convert strings to floats

I have a data object of the type: list[lists['string', 'string', floats]], but actually the floats are strings too, which I want to convert to floats. I tried the following but for some reason it still loops over the first two elements in the internal lists, but the if statement seems correct? Does anyone know what I’m doing wrong?

list_of_lists = [
    ['bla1', 'bla2', '1.', '2.', '3.', '4.'],
    ['bla3', 'bla4', '5.', '6.', '7.', '8.']
    ]

for idx_datapoint, datapoint in enumerate(list_of_lists):
    print(f'{datapoint = }')
    for idx_feature, feature_val in enumerate(datapoint):
        if idx_feature in (0, 1):
            print(f'{idx_feature = }, {feature_val = }')
            print(f'{float(feature_val) = }')
            list_of_lists[idx_datapoint][idx_feature] = float(feature_val)

Thank you for your help in advance!! I think I’m overlooking something small, so sorry in advance 😀

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 :

Keep in mind that some of the values of the lists have letters in them, so they cant be changed into floats. Other than that, this is how I would do it:

list_of_lists = [
    ['bla1', 'bla2', '1.', '2.', '3.', '4.'],
    ['bla3', 'bla4', '5.', '6.', '7.', '8.']
    ]

for i, list in enumerate(list_of_lists):
    for i2, v in enumerate(list):
        try:
            list_of_lists[i][i2] = float(v)
        except ValueError:
            pass  # change to whatever you want to do if you cant change it

I just tested it and it seems to work fine. Just change the ‘pass’ line to whatever you want to do with the values that have letters in them (like removing them or removing the letters).

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