user15649753
user15649753

Reputation:

how make a list unique and keep the index of eliminated items?

I have two lists. They have the same size and kind of related to each other. I wanna make one of them unique and eliminate the corresponding element in the other list. (So I need the index of eliminated item).Suppose we always keep the first one and eliminate the other identical items.

Example:

my_list=[['A','B','C'],['D','Q'],['O','W','S'],['D','Q'],['D','Q']]
sec_list=[[1,2,5],[3,4],[5,6,4],[7,8],[2,5]]

The result:

my_list=[['A','B','C'],['D','Q'],['O','W','S]]
sec_list=[[1,2,5],[3,4],[5,6,4]]

What I did:

I know how to make elements of a list unique by the following code:

Uni=[]
[Uni.append(i) for i in my_list if i not in Uni]

But it doesn't give me the index to delete corresponding items in the second list. I tried for loop:

index_remove=[]
for s,i in enumerate(my_list):
    for r,j in enumerate(my_list):
        if s!=r:
            if i==j:
                if s not in index_remove:
                    index_remove.append(s) 

But it gives me the index of all similar items. Not the one that should be removed.

Upvotes: 4

Views: 146

Answers (3)

Aniketh Malyala
Aniketh Malyala

Reputation: 2670

You can go over both arrays using a single for loop, along with an index variable for the second array:

my_list=[['A','B','C'],['D','Q'],['O','W','S'],['D','Q'],['D','Q']]
sec_list=[[1,2,5],[3,4],[5,6,4],[7,8],[2,5]]

result1 = []
result2 = []

ind = 0
for arr in my_list:
  if arr not in result1:
    result1.append(arr)
    result2.append(sec_list[ind])
  ind += 1

print(result1)
print(result2)

Upvotes: 0

not_speshal
not_speshal

Reputation: 23156

Since both your lists have the same structure, you could do:

unique_1 = [l for i, l in enumerate(my_list) if l not in my_list[:i]]
unique_2 = [sec_list[i] for i, l in enumerate(my_list) if l not in my_list[:i]]

>>> unique_1
[['A', 'B', 'C'], ['D', 'Q'], ['O', 'W', 'S']]

>>> unique_2
[[1, 2, 5], [3, 4], [5, 6, 4]]

If you want the indices of the eliminated items:

>>> [i for i,l in enumerate(my_list) if l in my_list[:i]]
[3, 4]

Upvotes: 0

Barmar
Barmar

Reputation: 781741

Use zip() to iterate over the two lists together. When you append an element to the first result, also append the corresponding element to the second result.

result1 = []
result2 = []
for my, sec in zip(my_list, sec_list):
    if my not in result1:
        result1.append(my)
        result2.append(sec)

Upvotes: 2

Related Questions