A
A
Andrew2021-11-02 11:53:07
Python
Andrew, 2021-11-02 11:53:07

How to remove elements from a list with the same ending?

Let's say we have a list:


l1 = ['Ivanov', 'Petrov', 'Sidorov', 'Pears', 'Apples', 'Table', 'Car', 'Lamp', '940345']

I need to remove all elements with the same ending (for example, elements with the same characters [-2:]), what is the most efficient and concise way to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-02
@rsytrade

To paraphrase - you need to remove from the list all elements for which there is at least one other element with matching N last characters. So?
Use collections.Counter.

l1 = ['Ивановы', 'Петровы', 'Сидоровы', 'Груши', 'Яблоки', 'Стол', 'Машина', 'Лампа', '940345']
N = 2
suffixes = collections.Counter( item[-N:] for item in l1 )
l2 = list( filter( lambda item: suffixes[item[-N:]] <= 1, l1 ) )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question