Reputation: 179
My task is to use a set to convert a list of duplicates to a list of unique numbers. However, I want to retain the positions.
Simple enough I thought; so I made a dictionary that first stores the original list's positions.
def get_positions(a):
positions = {}
for ele in a:
if not ele in positions:
positions[ele] = a.index(ele)
return positions
So lets say I have a list a = [1, 2, 4, 4, 5]
Positions will give me a dictionary of {0:1, 1:2, 2:4, 3:4, 4:5}
.
This however was unsuccessful because I repeated numbers will not get their positions stored.
Is there a way of achieving this?
Thanks.
UPDATE:
It seems I wasn't clear. I need to use a set. So, I get a list a=[1,2,4,4,5] and I must convert it to a set to erase the duplicates. Then, I need to get a list with the elements in the same order. (It's an assignment problem)
Upvotes: 0
Views: 456
Reputation: 11050
I think you are going about this the wrong way. You are trying to remove duplicates from a list, but you are having a problem which you are trying to solve by having the positions of things in the list without duplicates being removed. Instead, I think it would be better to do something more like this:
def remove_duplicates(seq):
new_list = []
for i in seq:
if i not in new_list:
new_list.append(i)
return new_list
One fairly readable way to do this, using sets (with the corresponding O(1) membership testing (but with higher memory usage) is this:
def remove_duplicates(seq):
seen = set()
new_list = []
for i in seq:
if i not in seen:
new_list.append(i)
seen.add(i)
return new_list
This answer to the same question also uses sets, and is quite possibly faster (but using a bit hacky in using and not set.add
).
Upvotes: 2
Reputation: 12371
you want an OrderedSet. but this sounds like a homework problem, and i don't know if they would accept that.
Upvotes: 0
Reputation: 129477
You can use an OrderedDict
:
>>> from collections import OrderedDict
>>>
>>> a = [1, 2, 4, 4, 5]
>>>
>>> list(OrderedDict.fromkeys(a))
[1, 2, 4, 5]
You can also use a plain set
for this. One common way is:
>>> a = [1, 2, 4, 4, 5]
>>>
>>> seen = set()
>>> [x for x in a if x not in seen and not seen.add(x)]
[1, 2, 4, 5]
The trick here is that not seen.add(x)
will always be True
because add()
always returns None
. In practice, I would always use the OrderedDict
approach.
See also: How do you remove duplicates from a list in Python whilst preserving order?
Upvotes: 6
Reputation: 1446
This can be done with a loop and an if statement:
>>> oldlist = [1,2,3,3,4,5,4,5,6,2,3,5,7,8,3,3,3,9]
>>> newlist = []
>>> for x in oldlist:
... if not x in newlist:
... newlist.append(x)
...
>>> newlist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Upvotes: 1