iterate through sublists, compare and print what is missing

Question:

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!

Asked By: deksa89

||

Answers:

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']]
Answered By: RomanPerekhrest

You can achieve desired behavior with next method of generator that finds first today in string. Generator allows you not to check every element in sublist but just find first one.

Also your date is always in yyyy_mm_dd format, you can hardcode 11 symbols slice.

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'

result = [[] if next((file for file in sublist if today in file), None) else sublist[0][:-11] for sublist in x]
print(result)

Output:

[[], 'forms']
Answered By: pL3b
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.