How to scan previous list values in order to add a new composite list value?
Try this:
import re
a = [ [1067.8420440505633, 'C2NW'], [1287.3506292298346, 'C1NW'], [1363.9930359848377, 'C2W'], [1483.1371597306722, 'C1W'], [1767.6648314715849, 'C2NW'] ]
Timeline, statuses = zip(*a)
WorkingOrNot = []
current_statuses = {}
# Regex pattern to extract component and working/not working status
pattern = re.compile(r'(C\d+)(\w+)')
for status in statuses:
match = pattern.search(status)
# Set the key corresponding to component to the status (W or NW)
current_statuses[match[1]] = match[2]
WorkingOrNot.append(''.join(map(''.join, sorted(current_statuses.items(), key=lambda kv: int(kv[0][1:])))))
print(WorkingOrNot)
# ['C2NW', 'C1NWC2NW', 'C1NWC2W', 'C1WC2W', 'C1WC2NW']
The code is fairly self-explanatory. The only confusing parts may be
Timeline, statuses = zip(*a)
which is equivalent to
TimeLine = [item[0] for item in a]
statuses = [item[1] for item in a]
And this line:
WorkingOrNot.append(''.join(map(''.join, sorted(current_statuses.items(), key=lambda kv: int(kv[0][1:])))))
This does nothing other than format the output into the desired format form its dictionary form. Sorting the dictionary my component ID, join the key (component) and value ('W'
or 'NW'
), then join all of that.