从列表中有效删除重复项[重复项]

问题描述 投票:1回答:2

晚上好。我有一个带有邮政编码和相关信息的Excel文件。这些邮政编码有很多重复项。我想通过将所有邮政编码都放在一个没有重复的列表中来弄清楚我拥有哪些邮政编码。该代码有效,但是运行非常缓慢(耗时100秒以上),并且想知道我该怎么做才能提高效率。

我知道每次必须检查整个列表中是否有重复项,这会导致效率低下,但是我不确定如何解决。我也知道,遍历每一行可能不是最好的答案,但是我还是很新,现在被困住了。

提前感谢。

import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    for i in range(sheet.nrows):
        if str(sheet.cell(i,0).value) in zipsInSheet:
            pass
        else:
            zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()
python performance xlrd zipcode
2个回答
2
投票

如果要避免重复,那么您绝对应该考虑在python中使用Sets。参见here

我要做的是创建一个集合,然后将所有元素简单地添加到集合中;请注意,集合是项目的无序唯一集合。一旦添加了所有数据,您就可以将集合中的所有元素添加到工作表中。因此,这避免了冗余数据。



import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    data = set()

    for i in range(sheet.nrows):
      data.add(str(sheet.cell(i,0).value)

    #now add all elements in the set to your sheet
    for i in range(len(data)):
      zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()

1
投票

我通常只是将其转换为集合。集是你的朋友。它们比列表快得多。除非您有意地需要或想要重复,否则请使用集。

https://docs.python.org/3.7/tutorial/datastructures.html?highlight=intersection#sets

© www.soinside.com 2019 - 2024. All rights reserved.