I have a dataset I need to interpret in order to reconstruct a signal to analyse. To do this I use a large number of if, elif statements. I was wondering if there is a more elegant way to do this?
This is my code:
for line in data:
if line[:2] == '10':
capstart = 1
if capstart == 1:
if line[:2] == 'e3':
reconstruct(int(line[2:6],16), int(line[6:10],16))
elif line[:2] == '02':
if line[8:] == '20':
REDoffset = int(line[2:4],16)
REDledlvl = int(line[4:6],16)
REDgain = int(line[6:8],16)
if line[8:] == '10':
IRoffset = int(line[2:4],16)
IRledlvl = int(line[4:6],16)
IRgain = int(line[6:8],16)
elif line[:2] == '10':
if line[2:4] == '00':
pulse_length_lo = int(line[4:],16)
if line[2:4] == '01':
pulse_length_hi = int(line[4:],16)
if line[2:4] == '02':
pulse_ir_on = int(line[4:],16)
if line[2:4] == '03':
pulse_red_on = int(line[4:],16)
if line[2:4] == '04':
pulse_led_switch_time = int(line[4:],16)
if line[2:4] == '05':
dark_worn_threshold = int(line[4:],16)
if line[2:4] == '06':
imu_accel_range = int(line[4:],16)
if line[2:4] == '07':
imu_gyro_range = int(line[4:],16)
if line[2:4] == '08':
ls_duration = int(line[4:],16)
if line[2:4] == '09':
imu_interval = int(line[4:],16)
if line[2:4] == '0a':
timestamp_lo = int(line[4:],16)
if line[2:4] == '0b':
timestamp_hi = int(line[4:],16)
if line[2:4] == '0c':
ADC_MAX = int(line[4:],16)
if line[2:4] == '0d':
ADC_offset = int(line[4:],16)
if line[2:4] == '0e':
lightsensor_has_red = int(line[4:],16)
if line[2:4] == '0f':
IR_worn_current = int(line[4:],16)
if line[2:4] == '10':
IR_worn_offset = int(line[4:],16)
if line[2:4] == '11':
IR_worn_threshold = int(line[4:],16)
if line[2:4] == '12':
accel_num_bits = int(line[4:],16)
if line[2:4] == '13':
gyro_num_bits = int(line[4:],16)
if line[2:4] == 'ff':
sensor_end_status = line[4:]
else:
other.append(line)
Note that the 'data' list contains a number of packets in hex, where the fisrt byte (first two chars in the string) indicate the packet type, and within each packet type, I need to separate the strings and isolate the data containded there.
I you could point me where to look it would be great! The code works, but I'd like it to be more elegant.