使用嵌套for循环

时间:2015-07-18 08:13:45

标签: python excel loops xlrd

使用python 3.4,我正在处理一个较大程序的一小部分问题。对于这部分,我需要比较两个excel表的列A和Bookings.xlsx'和'强迫.xxx'。

A栏包含两张表中的预订编号,bookings.xlsx包含forced.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]]

据我所知,这应该看看“强迫”中的每个预订号码。 sheet(变量Fnum)并将其与预订'进行比较。 sheet(变量Bnum),当找到匹配项时,它会将该行中的相应数据添加到列表“强制对象”中。

问题是在这个循环结束后,列表为空但它应该找到632个匹配,因此包含632个嵌套列表。我确定这是一个非常简单的解决方案,但我无法弄明白。

1 个答案:

答案 0 :(得分:0)

cell()更改为cell_value()

Fnum = forced_sheet.cell_value(force_row, 0)
Bnum = bookings_sheet.cell_value(book_row,0)

或将FnumBnum的类型转换为str会根据内容字符串对它们进行比较。

if str(Fnum) == str(Bnum):

请注意cell()会返回xlrd.sheet.Cell个对象。

并且Cell类的xlrd没有__eq__()__ne()__来支持相等运算符。在此处阅读更多内容:https://docs.python.org/2/reference/datamodel.html#object.ne

您可以在此处查看xlrd的来源https://github.com/python-excel/xlrd/blob/master/xlrd/sheet.py

来自The xlrd Module

  

单元格(rowx,colx)[#]

     

给定行和列中的单元格对象。

     

cell_value(rowx,colx)[#]

     

给定行和列中单元格的值。

因此,FnumBnum的类型为xlrd.sheet.Cell,而不是str

>>> type(Fnum)
<class 'xlrd.sheet.Cell'>
>>>
>>> type(Bnum)
<class 'xlrd.sheet.Cell'>

但在使用cell_value()时,

>>> type(Fnum)
<class 'str'>
>>>
>>> type(Bnum)
<class 'str'>

然后你可以根据它们的字符串值来比较它们。

相关问题