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.
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