Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete end of element from a list if the element ends with an element from another list

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']
like image 755
m_h Avatar asked Mar 03 '23 03:03

m_h


2 Answers

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.

like image 107
FatihAkici Avatar answered May 10 '23 23:05

FatihAkici


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)
like image 27
Tom J Muthirenthi Avatar answered May 10 '23 23:05

Tom J Muthirenthi