Python 筛选出重复的表项

Python 筛选出重复的表项,python,csv,file-io,Python,Csv,File Io,我想读入T1,然后写出T2(注意两者都是.csv)。 T1包含重复的行;我不想在T2中重复写 T1 T2 目前,我有一个极其缓慢的代码来过滤重复的代码: no_dupes = [] for row in reader: type = row[0] year = row[1] index = type,age values_list = row[2:] if index not in no_dupes: for i,j in enumer

我想读入T1,然后写出T2(注意两者都是.csv)。 T1包含重复的行;我不想在T2中重复写

T1

T2

目前,我有一个极其缓慢的代码来过滤重复的代码:

no_dupes = []

for row in reader:
    type = row[0]
    year = row[1]
    index = type,age
    values_list = row[2:]

    if index not in no_dupes:
        for i,j in enumerate(values_list):
            line = [type, year, str(i+1), str(j)]
            writer.writerow(line) #using csv module
            no_dupes.append(index)
当T1变大时,我无法举例说明这段代码有多慢


在我写入T2时,有没有更快的方法从T1中过滤出重复项?

如果可能,将读卡器转换为一个集合并在该集合上迭代,则不可能有DUP

如果可能,将读卡器转换为一个集合并在该集合上迭代,则不可能有DUP

我想您想要这样的东西:

no_dupes = set()

for row in reader:
    type, year = row[0], row[1]
    values_list = row[2:]

    for index, value in enumerate(values_list, start=1):
        line = (type, year, index, value)
        no_dupes.add(line)

for t in no_dupes:
    writer.writerow(t)

我想你想要这样的东西:

no_dupes = set()

for row in reader:
    type, year = row[0], row[1]
    values_list = row[2:]

    for index, value in enumerate(values_list, start=1):
        line = (type, year, index, value)
        no_dupes.add(line)

for t in no_dupes:
    writer.writerow(t)

我无法使用csv.reader()完成此操作;读卡器中的每一行都是一个列表。我无法使用csv.reader()实现这一点;读卡器中的每一行都是一个列表。至少,每次通过循环,您都要将
索引添加到
无重复列表中。因此:(1)将
no_dupes
更改为
set
,(2)将
index
添加到
no_dupes
中,每个循环只能添加一次。至少,每次通过循环,您都将
index
添加到
no_dupes
列表中。因此:(1)将
no_dupes
更改为
set
,(2)将
index
添加到
no dupes
,每个循环仅一次。谢谢!这大大加快了速度。谢谢!这大大加快了速度。
no_dupes = set()

for row in reader:
    type, year = row[0], row[1]
    values_list = row[2:]

    for index, value in enumerate(values_list, start=1):
        line = (type, year, index, value)
        no_dupes.add(line)

for t in no_dupes:
    writer.writerow(t)