2

I would like to delete all the elements from list of lists that appear more than once and am looking for a smoother solution than this: Removing Duplicate Elements from List of Lists in Prolog

I am not trying to remove duplicated lists inside of the parent list like here: How to remove duplicates from nested lists

Consider this Int:

list = [
[1, 3, 4, 5, 77],
[1, 5, 10, 3, 4],
[1, 5, 100, 3, 4], 
[1, 3, 4, 5, 89], 
[1, 3, 5, 47, 48]]

Desired output:

new_list= [
[77],
[10],
[100], 
[89], 
[47, 48]]

Thanks. I am going to use this in Pandas: the new_list will serve as a new column with unique values on each row compare to the original column.

2 Answers 2

2

There may be sleeker ways, but this works:

from collections import Counter

mylist = [
[1, 3, 4, 5, 77],
[1, 5, 10, 3, 4],
[1, 5, 100, 3, 4], 
[1, 3, 4, 5, 89], 
[1, 3, 5, 47, 48]]


flat = [y for x in mylist for y in x]    
count = Counter(flat)
uniq = [x for x,y in count.items() if y == 1]
new_list = [[x for x in y if x in  uniq] for y in mylist]

which gives

[[77], [10], [100], [89], [47, 48]]
Sign up to request clarification or add additional context in comments.

Comments

1
for bi,lst in enumerate(l):
    for el in lst:
        for i in range(len(l)):
            if bi != i:
                if el in l[i]:
                    print(f'element:{el}')
                    print(f'passing over list:{l[i]}')
                    l[i].remove(el)
                    try: l[bi].remove(el)
                    except: continue

that one is not that useful but I see that usually other answers(including your linked posts) uses another modules so I tried different approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.