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

Python: Remove values that are duplicated in the previous list inside a nested list

Example of a given nested list:

nList = [[2,5,99,99],[-3,8,1,2,10],[1, 7,100,10]]

Expectations: Remove values that are duplicated in the previous list.

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

Expected Output:

oList = [[2, 5, 99], [-3, 8, 1, 10], [7, 100]]

My Codes:

def RemoveDup(nList):
    lst = []
    for i in nList:
        for j in i:
            if j not in lst:
                lst.append(j)            
    return lst 

>>> print(RemoveDup([[2,5,99,99],[-3,8,1,2,10],[1, 7,100,10]]))
>>> [2, 5, 99, -3, 8, 1, 10, 7, 100]

I still couldn’t figure out how to make the output a nested list like the expected output, any help and advice are appreciated!

>Solution :

As there is no "previous" element to compare against the first element in the nested list then it must be dealt with as is.

This may achieve the real objective:

nList = [[2,5,99,99],[-3,8,1,2,10],[1, 7,100,10]]

output = [nList[0]]

for e in nList[1:]:
    t = []
    for x in e:
        if x not in output[-1]:
            t.append(x)
    output.append(t)

print(output)

Output:

[[2, 5, 99, 99], [-3, 8, 1, 10], [7, 100]]

If duplicates need to be removed from the first element in the list then:

nList = [[2,5,99,99],[-3,8,1,2,10],[1, 7,100,10]]

output = []

t = []

for e in nList[0]:
    if e not in t:
        t.append(e)
output.append(t)
for e in nList[1:]:
    t = []
    for x in e:
        if x not in output[-1]:
            t.append(x)
    output.append(t)

print(output)

Output:

[[2, 5, 99], [-3, 8, 1, 10], [7, 100]]

Note:

The temptation to use sets should be avoided as the order of the output list may not be as expected

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