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?
CodePudding user response:
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.
CodePudding user response:
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)
CodePudding user response:
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 pandas:
import pandas as pd
out = pd.to_numeric(pd.Series(l).str.extract(r'(\d )', expand=False)
).mod(2).tolist()