Python:XLRD; 比较列长度

Sat*_*thy 6 python xlrd

我正在使用xlrdxls文件.我的xls文件有两列,我的要求是确保两列的行数相等.我从中了解到help(),我们有一个row_len()查找索引给出的行的长度,但无法找到任何col_len.你能帮忙吗?

这是我的代码

from xlrd import open_workbook
spread_sheet=open_workbook("simple.xls")
sheet1=spread_sheet.sheet_by_index(0)

#validates the no of columns in the Spread sheet
 if sheet1.ncols == 2:
  for sheet1_rows in range(sheet1.nrows):
    for sheet1_cols in range(sheet1.ncols):
        value=sheet1.cell(sheet1_rows,sheet1_cols).value
        source=sheet1.cell(sheet1_rows,0).value
        destination=sheet1.cell(sheet1_rows,1).value
    #ignores the Source and Destination Headers 
    if value not in ('Source','Destination'):
        print "Source is : %s \nDestination is : %s\n" %    (source,destination)
 else:
  print "XLS provided is not valid. Check the no of columns is 2"
Run Code Online (Sandbox Code Playgroud)

除了比较以下之外,还有其他一些选择

>>> print len(sheet1.col_values(0))
8
>>> print len(sheet1.col_values(1))
8
Run Code Online (Sandbox Code Playgroud)

谢谢你的回复@alecxe.而是在我的代码中添加更多行,我在下面找到了一些东西.请告知这项工作

 >>> print len(sheet1.col_values(0))
 6
 >>> print len(sheet1.col_values(1))
 6
 >>> sheet1.col_values(0)
 [u'A', 1.0, 1.0, 1.0, 1.0, 2.0]
 >>> sheet1.col_values(1)
 [u'B', 2.0, 2.0, 2.0, 2.0, '']
 >>> print len(filter(None,sheet1.col_values(1)))
 5
 >>>
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 6

您不能len(sheet.col_values(index))用于测量列中设置的单元格数(列长度).col_values长度总是等于sheet.nrows.

想象一下,你有以下几点input.xls:

A B
1 2
1 2
1 2
1 2
  2 
Run Code Online (Sandbox Code Playgroud)

然后len(sheet.col_values(0))将返回5(以及len(sheet.col_values(1))),这是不正确的.应该是4.

相反,最好使用这样的东西:

from itertools import takewhile
import xlrd


def column_len(sheet, index):
    col_values = sheet.col_values(index)
    col_len = len(col_values)
    for _ in takewhile(lambda x: not x, reversed(col_values)):
        col_len -= 1
    return col_len


book = xlrd.open_workbook("input.xls")
sheet = book.sheet_by_index(0)

print column_len(sheet, 0)  # prints 4
print column_len(sheet, 1)  # prints 5
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.