Home > OS >  Get list for duplicates on an other list python
Get list for duplicates on an other list python

Time:06-29

I need help to get a list from an other :

input :

[[1, 1], [1, 1], [2, 2], [1, 1], [1, 1], [2, 2], [3, 3], [4, 4]]

output wanted :

[0, 0, 1, 0, 0, 1, 2, 3]

I tried to use enumerate but I fail, any suggestion ?

Edit : Every time I meet a new element in the list, I associate this new element with a number (start from 0 and 1 every new element) and if I recognize it later I put the same number, so [1,1] --> 0 because is the first element we met and [2,2] --> 1 etc...

Okay I found a solution :

  • One more thing before, my example is bad because I can have [1,2] in element of the list for input
  • the solution I found is
line = [[1, 1], [1, 1], [2, 2], [1, 1], [2, 1], [2, 2], [3, 3], [4, 4]]
p = []
line_not = []
k = 0
for i in range (len(line)):
    if line[i] in line[:i]:
        p.append(line_not[:k].index(line[i]))
    else:
        p.append(k)
        line_not.append(line[i])
        k =1

the output is :

[0, 0, 1, 0, 2, 1, 3, 4]

If u have a better solution, tell me !

CodePudding user response:

First build a dictionary that does the assocation of each unique element with a number:

>>> x = [[1, 1], [1, 1], [2, 2], [1, 1], [1, 1], [2, 2], [3, 3], [4, 4]]
>>> d = {}
>>> for [i, _] in x:
...     if i not in d:
...         d[i] = len(d)
...

and then you can easily build your output list by doing lookups in that dictionary:

>>> [d[i] for [i, _] in x]
[0, 0, 1, 0, 0, 1, 2, 3]

CodePudding user response:

this would work in your current example, but it is not a comprehensive solution. Without context its hard to understand what you are trying to achieve, so use with care:

import numpy as np
inp = [[1, 1], [1, 1], [2, 2], [1, 1], [1, 1], [2, 2], [3, 3], [4, 4]]
out = np.array([i[0] for i in inp]) - 1
print(out)  # result: [0 0 1 0 0 1 2 3]
  • Related