Reputation: 21
Say I have a list of list
X=[[0,0,0,3,4],[8,8,9,2,8,2]]
How do I make it so that each sublist will only contain a repeated number once:
Like this new list:
XNew=[[0,3,4],[8,9,2]]
Upvotes: 0
Views: 59
Reputation: 7821
If you need to keep the order of your numbers, you can't use sets. This would keep the original order:
lst = [[0, 0, 0, 3, 4], [8, 8, 9, 2, 8, 2]]
new_lst = []
for sub_lst in lst:
seen = set()
new_sub = []
for item in sub_lst:
if item not in seen:
new_sub.append(item)
seen.add(item)
new_lst.append(new_sub)
print new_lst # [[0, 3, 4], [8, 9, 2]]
Upvotes: 0
Reputation: 32189
You can use set
for that:
new_x = [list(set(i)) for i in old_x]
Sets are a collection of unique elements and therefore create a set of unique values when a list of duplicate values is cast as a set. You can then convert the set back to a list and get the desired result.
>>> old_x = [[0,0,0,3,4],[8,8,9,2,8,2]]
>>> new_x = [list(set(i)) for i in old_x]
>>> print new_x
[[0,3,4],[8,9,2]]
Upvotes: 5