Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match element then remove both elements

My list consists on several items:

["book","rule","eraser","clipboard","pencil",etc]

Let say I have an element ["book"] and I want to match with another element ["rule"] with the same len (4). then I want to remove both elements from the list.

["eraser","clipboard","pencil",etc]

I tried using a for loop and zip(lists, lists[1:]) but I can only remove the elements next to each other while other elements (like papers and pencil, len = 6) are never removed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to remove same length words and have a final list with only the words whose length has no match or found no pair. For example:

["book","rule","eraser","clipboard","pencil","book"]

then the final list will be:

["clipboard","book"]

as book and clipboard found no pair.

>Solution :

You can try:

from collections import Counter

lst = ["book", "rule", "eraser", "clipboard", "pencil", "book"]

c = {k: v % 2 for k, v in Counter(map(len, lst)).items()}

out = []
for v in reversed(lst):
    if c[len(v)] == 1:
        out.append(v)
    c[len(v)] -= 1


print(out[::-1])

Prints:

['clipboard', 'book']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading