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

Convert a list of strings to a list of [0.0 or 1.0]

I have couple of lists and one of them looks like this :

['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27', ...] with 100 shapes in the list.
If the shape number is even, then convert it to 0.0, which is a float number.
If the shape number is odd, then convert it to 1.0, which is also a float number.
The result list should be like [1.0, 0.0, 1.0, 0.0, 1.0, 1.0, ...].

How could I convert the list easily?

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 :

input_list = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']


def converter(s: str) -> float:
    shape_length = len('SHAPE')
    substr = s[shape_length:]
    try:
        shape_integer = int(substr)
    except ValueError:
        raise ValueError(f'failed to extract integer value from string {s}')
    if shape_integer % 2 == 0:
        # it's even
        return 0.0
    else:
        return 1.0


output_list = [converter(x) for x in input_list]
print(output_list)
[1.0, 0.0, 1.0, 0.0, 1.0, 1.0]

The function converter trims the number out of the SHAPE12 string, and attempts to convert it into an integer. Then it runs a modulus operation to determine if it’s odd or even, returning the appropriate float.

The list comp creates a new list by running each value of the input_list through this function.

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