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.
To have a better pythonic approach, You can convert it into a list comprehension:
my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']
new_list =[]
for x in my_list:
for elem in extensions:
if x.endswith(elem):
y = x[:-len(elem)]
new_list.append(y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With