Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Remove duplicate elements in lists and sublists; and remove full sublist if duplicate

Is there is any function or way to achieve this recursively in python 2.7 ?

Input : ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P']]
Output : ['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]

Remove duplicate 'P' in sublist1 as duplicate

Input : ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P'], ['or', 'P', '-R', 'P']]
Output : ['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]

Remove duplicate 'P' in sublist1 as duplicate as well remove sublist3 as duplicate of sublist1

Thanks

like image 424
skool99 Avatar asked Mar 20 '26 11:03

skool99


1 Answers

I think you have to create a custom remove duplicate function inorder to preserve order of sublists.Try this:

def rem_dup(lis):
    y, s = [], set()
    for t in lis:
        w = tuple(sorted(t)) if isinstance(t, list) else t
        if not w in s:
            y.append(t)
            s.add(w)
    return y

inp = ['and', ['or', 'P', '-R', 'P'], ['or', '-Q', '-R', 'P'], ['or', 'P', '-R', 'P']]

out = [rem_dup(i) if isinstance(i, list) else i for i in rem_dup(inp)] 

>>>out
['and', ['or', 'P', '-R'], ['or', '-Q', '-R', 'P']]
like image 71
itzMEonTV Avatar answered Mar 23 '26 01:03

itzMEonTV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!