2015-12-29 110 views
1

我有一個包含一堆值的列表。我首先試圖找到帶有'MB'的項目,然後總結這些值。例如第一個「文字:u'3 MB」。我想要得到這個項目並且總結出在這種情況下將是3的值,並且對於具有「MB」的下一個項目在內部做同樣的處理。在列表中搜索並總結

代碼(到目前爲止):

#!/usr/bin/python 
import xlrd 
xl_workbook = xlrd.open_workbook("E:\usage.xls") 

sheet_names = xl_workbook.sheet_names() 
print('Sheet Names', sheet_names) 

xl_sheet = xl_workbook.sheet_by_index(0) 
print ('Sheet name: %s' % xl_sheet.name) 

liste=[] 
sum=0 

num_cols = xl_sheet.ncols # Number of columns 
for row_idx in range(0, xl_sheet.nrows): # Iterate through rows 
    for col_idx in range(0, num_cols): # Iterate through columns 
     cell_obj = xl_sheet.cell(row_idx, col_idx) # Get cell object by row, col 
     liste.append(cell_obj) 
     #print ('cell_obj: [%s]' % (cell_obj)) 

for item in liste: 
    if "MB" in item: 
      print item 

我收到此錯誤:

 if "MB" in item: 
TypeError: argument of type 'Cell' is not iterable 

列表(包含):

[xldate:42340.671805555554, text:u'3 MB', empty:'', number:0.0, xldate:42340.5, text:u'12 MB', empty:'', number:0.0, xldate:42340.42820601852, text:u'10 MB', empty:'', number:0.0, xldate:42339.81946759259, text:u'8 MB', empty:'', number:0.0, xldate:42339.55652777778, text:u'6 MB', empty:'', number:0.0, xldate:42339.35625, text:u'10 MB', empty:'', number:0.0, empty:'', empty:'', empty:'', empty:'', empty:'', empty:'', text:u'Totalt:', number:1.01] 
+3

內容'liste'無效語法 – poke

回答

3

liste列表中包含的Excel Cell objects這是不是自己的字符串,所以你不能使用in運算符檢查值是否包含一些字符串。你需要使用value屬性來訪問字符串值,但你應該只爲文本單元也這樣做,否則,value將是一個不同的類型:

for cell in liste: 
    if cell.ctype == 1 and 'MB' in cell.value: 
     print cell.value 

然後,爲了得到數值從字符串,則需要通過刪除MB提取號碼,例如:那

totalMegaBytes = 0 
for cell in liste: 
    if cell.ctype == 1 and 'MB' in cell.value: 
     totalMegaBytes += int(cell.value.replace('MB', '')) 

print(totalMegaBytes) 
+1

離開了'INT(值)'在這種情況下,否則你會截斷這個值(例如'23 KB'會一個值'0.023'和'int()'就可以讓你零)。 – poke