0

Can someone help me removing duplicates from reading a file

def listaClientes():
    f = open("chamadas.txt","r").readlines()
    print("Clientes que fizeram chamadas: ")
    new_lines = []
    for line in f:
        parts = line.strip().split()
        chamada = (parts[0])
        print(chamada)

It gives me this (parts)

Clients: 
960373347, 960373347,930930597, 960373347,939999868

As you can see i have numbers repeated, how to prevent this in python?

Thanks

Xero Smith
  • 1,888
  • 1
  • 12
  • 19

3 Answers3

0

You are not doing anything to remove duplicates. use a set to keep only unique values.

Try this:

def listaClientes():
  f = open("chamadas.txt","r").readlines()
  print("Clientes que fizeram chamadas: ")
  new_lines = set()
  for line in f:
    parts = line.strip().split()
    chamada = (parts[0])
    lines = new_lines.add
    return [cli for cli in chamada if not (cli in new_lines or lines(cli))]
Alg_D
  • 2,061
  • 4
  • 25
  • 59
0
def listaClientes():
    f = open("chamadas.txt", "r").readlines()
    print("Clientes que fizeram chamadas: ")
    new_lines = []
    for line in f:
        parts = line.strip().split()
        chamada = (parts[0])
        if chamada not in new_lines:#here checking if there any exesting entry
            new_lines.append(chamada)
        print(chamada)
    #at last new_lines have the unique entries
Roushan
  • 3,558
  • 3
  • 20
  • 37
0

Well known Python trick:

>>> l = [1, 2, 2, 2, 3, 4, 4, 5]
>>> list(set(l))
[1, 2, 3, 4, 5]
Joe Iddon
  • 19,256
  • 7
  • 31
  • 50