-1

I want to remove duplicates from each row in a two dimensional list. The list is entered by a user and consists of words.

I wrote a code for removing dublicates from a 1D array like this:

from math import *

inputlist = [(x) for x in input("\nInput words separated with comma:\n").split(', ')]
remove_duplicate = tuple(set(inputlist))
print(f'\nTupel:\n {remove_duplicate}')

And then another code for entering two dimensional list:

from math import *

import numpy as np
m = int(input("rows: ")) # rows
n = int(input("columns: ")) # columns
print("\nEneter words:\n")
twodlist = []
for i in range(0,m):
    twodlist.append([])
    for j in range(0,n):
        twodlist[i].append(0)
        twodlist[i][j] = (input())

But I don't know how to combine the codes so I get the results I want. I don't want the duplicates removed by columns but only by rows.

  • 2
    Can you provide an example of input? – mozway Jan 30 '22 at 15:43
  • Let say we input some words to this list: [['hi', 'test', 'hi'], ['test', 'one', 'two'], ['one', 'test', 'one']] I want to conevert this to, delete every dublicate from each row: [['hi', 'test'], ['test', 'one', 'two'], ['one', 'test']] – PixelPrime Jan 30 '22 at 15:47
  • `[list({}.fromkeys(sl)) for sl in twodlist]` – dawg Jan 30 '22 at 16:03

2 Answers2

0

I would suggest to avoid inserting duplicates on the first place. A nice method is to use a dictionary that cannot have duplicated keys. Here only the keys of the dictionary matter:

from math import *

import numpy as np
m = int(input("rows: ")) # rows
n = int(input("columns: ")) # columns
print("\nEneter words:\n")
twodlist = []
for i in range(0,m):
    d = {}
    for j in range(0,n):
        d[input()] = None
    twodlist.append(list(d))
mozway
  • 194,879
  • 13
  • 39
  • 75
0

This should do the trick if you are using nested lists

a = [[1,1,2,2],[1,2,3,3],[1,1,1]]
remove_duplicate = list(map(list, map(set,a)))
print(remove_duplicate)

Output

[[1, 2], [1, 2, 3], [1]]
nuclearczy
  • 26
  • 4