XLRD:成功从2张表中提取2个列表,但列表比较不起作用

好,所以我有两张xlsx表,两张表都在索引1的第二列中有一个SIM卡号列表。 我已经成功地将两列的内容打印到我的PowerShellterminal中作为2个列表,以及在使用xlrd提取数据之后这些列表中的元素的数量。

第一张(他们的纸张)有454个条目,第二张(我们的纸张)有361张。我需要find在第二张纸上不存在的93,并把它们放入(unpaidSims)中。 我当然可以手动做到这一点,但是当我不可避免地需要再次这样做时,我想自动完成这个任务,所以我正在尝试编写这个python脚本。

考虑到python同意我有一个454条目列表和一个361条目列表,我想我只需要弄清楚一个列表比较,我研究了堆栈溢出,并尝试了3次与3种不同的解决scheme,但每次,当我使用该脚本生成第三个列表(unpaidSims)时,它表示454 …表示它没有删除在较小列表中重复的条目。 请指教。

from os.path import join, dirname, abspath import xlrd theirBookFileName = join(dirname(dirname(abspath(__file__))), 'pycel', 'theirBook.xlsx') ourBookFileName = join(dirname(dirname(abspath(__file__))), 'pycel', 'ourBook.xlsx') theirBook = xlrd.open_workbook(theirBookFileName) ourBook = xlrd.open_workbook(ourBookFileName) theirSheet = theirBook.sheet_by_index(0) ourSheet = ourBook.sheet_by_index(0) theirSimColumn = theirSheet.col(1) ourSimColumn = ourSheet.col(1) numColsTheirSheet = theirSheet.ncols numRowsTheirSheet = theirSheet.nrows numColsOurSheet = ourSheet.ncols numRowsOurSheet = ourSheet.nrows # First Attempt at the comparison, but fails and returns 454 entries from the bigger list unpaidSims = [d for d in theirSimColumn if d not in ourSimColumn] print unpaidSims lengthOfUnpaidSims = len(unpaidSims) print lengthOfUnpaidSims print "\nWe are expecting 93 entries in this new list" # Second Attempt at the comparison, but fails and returns 454 entries from the bigger list s = set(ourSimColumn) unpaidSims = [x for x in theirSimColumn if x not in s] print unpaidSims lengthOfUnpaidSims = len(unpaidSims) print lengthOfUnpaidSims # Third Attempt at the comparison, but fails and returns 454 entries from the bigger list unpaidSims = tuple(set(theirSimColumn) - set(ourSimColumn)) print unpaidSims lengthOfUnpaidSims = len(unpaidSims) print lengthOfUnpaidSims 

根据xlrd Documentation , col方法返回“给定列中的Cell对象序列”。

它没有提到任何有关Cell对象的比较。 挖掘来源 ,似乎他们没有将任何比较方法编入课程。 因此, Python文档指出对象将通过“对象标识”进行比较。 换句话说,除非它们是Cell完全相同的实例,否则比较将是False ,即使它们包含的值是相同的。

您需要比较Cellvalue 。 例如:

 unpaidSims = set(sim.value for sim in theirSimColumn) - set(sim.value for sim in ourSimColumn)