[英]Python : XLRD; compare the columns length
我正在使用xlrd
處理xls文件。 我的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"
除了比較以下之外,還有其他一些選擇
>>> print len(sheet1.col_values(0))
8
>>> print len(sheet1.col_values(1))
8
謝謝你的回復@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
>>>
您不能使用len(sheet.col_values(index))
來測量列中設置的單元格數(列長度)。 col_values
長度始終等於sheet.nrows
。
想象一下,你在input.xls
有以下input.xls
:
A B
1 2
1 2
1 2
1 2
2
然后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
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.