I am trying to iterate through sublists and return name of the element that doesn’t match with today’s date. Example:
x = [['service_2023_01_10', 'service_2023_01_11', 'service_2023_01_12'], ['forms_2023_01_10', 'forms_2023_01_11']]
today = '2023_01_12'
and my result should be:
result = [[], ['forms']]
because elements that contain ‘forms’ doesn’t have today’s date in it.
This was my solution for similar task but I can’t make it work for this one:
result = [[e.split("_")[0] for e in sublist if "_".join(e.split("_")[-3:]) == today] if any([ "_".join(e.split("_")[-3:]) == today for e in sublist]) else [] for sublist in x]
this one returns: [['service'], []] but it should be the opposite.
Can you help me with it. Thank you!
>Solution :
This can be easily achieved using any and str.partition functions:
x = [['service_2023_01_10', 'service_2023_01_11', 'service_2023_01_12'], ['forms_2023_01_10', 'forms_2023_01_11']]
today = '2023_01_12'
res = [[] if any(today in w for w in sub_l) else [sub_l[0].partition('_')[0]] for sub_l in x]
print(res)
[[], ['forms']]