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

Question:

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?

Asked By: mario119

||

Answers:

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.

Answered By: Danielle M.

This code should do it:

array = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']
float_array = []
for item in array:
    if int(item[6:8]) % 2 == 0:
        float_array.append(0.0)
    else:
        float_array.append(1.0)
print(float_array)
Answered By: sofuslund

If you have a list, you can use a list comprehension and the modulo (%) operator:

l = ['SHAPE69', 'SHAPE48', 'SHAPE15', 'SHAPE28', 'SHAPE33', 'SHAPE27']
out = [int(s.removeprefix('SHAPE'))%2 for s in l]

NB. removeprefix requires python 3.9+, for earlier versions:

out = [int(s[5:])%2 for s in l]

Output:

[1, 0, 1, 0, 1, 1]

Variant with :

import pandas as pd

out = pd.to_numeric(pd.Series(l).str.extract(r'(d+)', expand=False)
                    ).mod(2).tolist()
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.