Home > Enterprise >  What function would I used to remove duplicate numbers in a list?
What function would I used to remove duplicate numbers in a list?

Time:05-05

I have 2 different lists that I combine into one list (list3). How would I remove the duplicates in the list?

note: can't use set() method

CodePudding user response:

s = []
for i in list3:
   if i not in s:
      s.append(i)

CodePudding user response:

import pandas as pd
pd.unique(list3).tolist()

CodePudding user response:

import numpy as np
np.unique(list3).tolist()

CodePudding user response:

itertools to the rescue.

from itertools import groupby

data = [5, 4, 3, 2, 1, 1, 2, 4, 8, 16, 2]

data = [g[0] for g in groupby(sorted(data))]
print(data)

This will give you [1, 2, 3, 4, 5, 8, 16].

CodePudding user response:

Evil stuff for a list with non-negative integers. Bonus: the resulting list is sorted.

data = [5, 4, 3, 2, 1, 1, 2, 4, 8, 16, 2]
pool = [False] * (max(data)   1)
for value in data:
    pool[value] = True
data = [i for i, j in enumerate(pool) if j]
print(data)
  • Related