在列表中搜索并总结

时间:2015-12-29 11:51:52

标签: python list sum

我有一个包含一堆值的列表。我首先尝试使用' 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.501238425924, 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]

1 个答案:

答案 0 :(得分:2)

您的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)