I have this code:
all_jobids = ['270', '271', '274', '278', '|_279', '|_280', '|_281', '288', '289', '|_290', '|_291', '298',
'299', '|_300', '|_301', '|_302', '|_303', '308']
intjobs = []
for entry in all_jobids:
sub_id = 0
try:
current_id = int(entry)
intjobs.append(current_id)
# except ValueError:
# sub_id = int(entry[2:])
# last_id = intjobs[-1]
# intjobs[-1] = [last_id].append(sub_id)
except ValueError:
sub_id = int(entry[2:])
if intjobs[-1] is list:
intjobs[-1].append(sub_id)
else:
last_id = intjobs[-1]
intjobs[-1] = [last_id].append(sub_id)
# intjobs[last_id] = [last_id].append(int(current_id[2:]))
print(entry, current_id, sub_id)
last_id = current_id
print(intjobs)
and have this output:
[270, 271, 274, None, 288, None, 298, None, 308]
but I want this (dots are just for shorter display):
[270, 271, 274, [278, ..., 281], 288, [289, 290, 291], 298, [299, ..., 303], 308]
So what I want is a list with optional sublists. I already looked after other Q&A (e.q. Make Python Sublists from a list using a Separator but it's not the same.
Using
try .. except
to catchValueError
exceptions, you can get the desired output like below:Output: