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?
>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.