clean a list from doubles?? Help

I guys, i’m working on a script, but i’ve problem on removing double value in a list,

the list is formatted in this way: a = [(x,y),(k,j),…] ans so on,

the thing i want to do is to remove the repeated value starting from the end of the list, i want to do this because, virtually, each element have an index(a[i]) that i use for vertex so i’ can’t lost the the value at that index.

so i need to remove double from the end to the start of the list. there is a way to do this???

I think this should help:


for item in a:
    if a.count(item) >1:
        a.remove(item)




Downside is that the last occurance of the double value stays in the list and the first are deleted.

Otherwise you can create a new list


new_list = []


for item in a:
    if not item in new_list:
        new_list.append(item)

and work with the new list from then on

Hi rebellion,

Here’s the code I came up with;

seen = set()
add = seen.add
c = [i for i in a if ((i not in seen) and (add(i) is None))]

For those interested in how this works:

  • Create a set to store the unique objects which have been processed. Use a set because it has fast membership testing.
  • Store the method to add an object to the set.
  • For each element in a, if it hasn’t been seen before then add it to c and add it to the seen set.

Hope that helps.

Cheers,
Truman

or convert list to set and set to list

Hi PKHG,

That was my first thought too, however, converting a list to a set and back again does not maintain the order of the elements. If the order doesn’t matter then that way works fine.

Cheers,
Truman

hi guys, thanks for reply!! but sephiroth give me the inspiration, and i think i’ve solved the problem. the code of sephiroth, remove double , but if there are more then two repeat it dont see it, and it don’t remove from the end to the first.

so this is the code i used:

a.reverse()

    for item in a:

        while a.count(item) >1:
              a.remove(item)

   a.reverse()

the explanation:

a.reverse invert the list so i can remove the last element by first.
then i substitute “if” with “while” (it works i don’t know why ;P)

and then i reverse again the list