删除重复python

时间:2018-01-23 21:39:21

标签: python-3.x

有人可以帮我删除重复的文件吗

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)

它给了我这个(部分)

Clients: 
960373347, 960373347,930930597, 960373347,939999868

你可以看到我重复了数字,如何在python中阻止这个?

由于

3 个答案:

答案 0 :(得分:0)

您没有做任何事情来删除重复项。 使用集合只保留唯一值。

试试这个:

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))]

答案 1 :(得分: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

答案 2 :(得分:0)

众所周知的Python技巧:

>>> l = [1, 2, 2, 2, 3, 4, 4, 5]
>>> list(set(l))
[1, 2, 3, 4, 5]