在使用python3.4时,我在处理一个较大程序的一小部分时遇到了问题。对于这一部分,我需要比较两个excel表格的A列'预订.xlsx'和'强制.xlsx'. 在
A列包含两张表中的预订号码,预订.xlsx包含中每个预订号码所需的数据(在同一行中)强制.xlsx在
这是我遇到麻烦的部分。在
reloc_sheet = reloc_book.sheet_by_index(0)
forced_sheet = forced_book.sheet_by_index(0)
bookings_sheet = bookings_book.sheet_by_index(0)
forced_rentals = []
for force_row in range(4,forced_sheet.nrows): #row 0:3 are headers
Fnum = forced_sheet.cell(force_row, 0)
for book_row in range(1,bookings_sheet.nrows): #row 0 is a header
Bnum = bookings_sheet.cell(book_row,0)
if Fnum == Bnum:
booNum = str(bookings_sheet.cell(book_row,0))
renCODate = bookings_sheet.cell(book_row,2)
renCOLoc = str(bookings_sheet.cell(book_row,4))
renUnit = str(bookings_sheet.cell(book_row,13))
renAgent = str(bookings_sheet.cell(book_row,12))
forced_rentals += [[booNum,renCODate,renCOLoc,renUnit,renAgent]]
据我所知,这应该查看“强制”表(变量Fnum)中的每个预订编号,并将其与“预订”表(变量Bnum)进行比较,当找到匹配项时,它会将该行的相应数据添加到“强制租赁”列表中。在
问题是在这个循环结束后,列表是空的,但它应该找到632个匹配项,因此包含632个嵌套列表。我相信这是一个非常简单的解决办法,但我想不出来。在
我已经解决了我的问题。首先,这里是一段代码,现在可以使用:
1)一个all number
^{pr2}$Bnum
或Fnum
变量可能是字符串,例如'7123456'或浮点7123456.0,它没有被识别为相同的值。转换为string by只会使浮点“7123456.0”再次变得不同。我通过以下方法解决了这个问题:此操作将浮点转换为字符串并删除“.0”
2)下一个问题是当我意识到并不是所有的预订号码(
Bnum
和Fnum
变量)都将包含/1。租金7123456和租金7123456/1是相同的,但我们的报表服务器(生成excel表)将交替使用这两种格式,这意味着强制表可能有7123456,而预订表可能有7123456/1。为了弥补这一点,我添加了以下内容:这将查找任何以'/1'结尾的预订号码并将其删除。在
将
cell()
更改为cell_value()
或者将
^{pr2}$Fnum
和Bnum
的类型转换为str
将根据它们的内容字符串对它们进行比较。在请注意,
cell()
返回一个xlrd.sheet.Cell
对象。在xlrd的}来支持相等运算符。阅读更多信息:https://docs.python.org/2/reference/datamodel.html#object.ne
Cell
类没有__eq__()
和{您可以在这里查看xlrd的源代码,https://github.com/python-excel/xlrd/blob/master/xlrd/sheet.py。在
来自The xlrd Module:
因此,}的类型是}。在
Fnum
和{xlrd.sheet.Cell
,而不是{但是在使用
^{4}$cell_value()
时然后可以根据字符串值对它们进行比较。在
相关问题 更多 >
编程相关推荐