I have the following two lists. If my_list ends with an extension from extensions, then it should be removed. I can't seem to find a solution that doesn't require too many lines of code.
Input:
my_list = ['abc_sum_def_sum', 'abc_sum_def_mean', 'abc_sum', 'abc_abc']
extensions = ['_sum', '_mean']
Output:
new_list = ['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']
One-liner list comprehension:
new_list = [min(e[:(-len(ext) if e.endswith(ext) else len(e))] for ext in extensions) for e in my_list]
Result:
['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']
Explanation:
What this does is basically loops over my_list
, checks if its element e
has either of the two extensions
items at its end. If it does, it trims that extensions piece down. If it doesn't, leaves that element of my_list
untouched. It basically first does this (without the min
applied):
[[e[:(-len(ext) if e.endswith(ext) else len(e))] for ext in extensions] for e in my_list]
which produces:
[['abc_sum_def', 'abc_sum_def_sum'],
['abc_sum_def_mean', 'abc_sum_def'],
['abc', 'abc_sum'],
['abc_abc', 'abc_abc']]
and then applies min
to collect the smaller item of each pair. That min
corresponds to either the trimmed-down version of each element, or the untouched element itself.