如何在字典值中进行计算

时间:2016-11-17 10:41:03

标签: python

任务:
计算q1_weight / q1value并将其存储在q1_normalize中。我怎么能这样做?

数据集
项目q1_weight q1_value厂商
I1 30 21 M1
I2 39 25 M2

代码:

import xlrd
import xlwt
from xlsxwriter import Workbook
data=[]
workbook=xlrd.open_workbook('Data.xlsx')
worksheet=workbook.sheet_by_name('Sheet1')
worksheet=workbook.sheet_by_index(0)
num_rows=worksheet.nrows
num_cols=worksheet.ncols
#======================================================================
Printing all the values of excel sheet
for row_index in range(0,num_rows):
    print('-'*40)
    print   ('Row: %s' % row_index)
    for col_index in range(0,num_cols):
        cell_obj=worksheet.cell(row_index,col_index)
        print('Column: [%s] Cell_oj: [%s]' % (col_index,cell_obj))
print("+"*100)
#=======================================================================

keys = [worksheet.cell(0, col_index).value for col_index in range(worksheet.ncols)]
dict_list = []
for row_index in range(1, worksheet.nrows):
    d = {keys[col_index]: worksheet.cell(row_index, col_index).value
         for col_index in range(worksheet.ncols)}
    dict_list.append(d)
Manufact=raw_input("Enter Manufacturer name: ")
string=Manufact.title()
temp=next(item for item in dict_list if item["Manufacturer"] == string)

ordered_list=["Items","q1_weight","q1_value","q1_normalize","q2_weight","q2_value", "q2_normalize","q3_weight","q3_value","q3_normalize","q4_weight","q4_value","q4_normalize", "q5_weight","q5_value","q5_normalize","Manufacturer"]
# for row_index in range(0):
#     d = {keys[col_index]: worksheet.cell(row_index, col_index).value
#          for col_index in range(worksheet.ncols)}
#     h.append(d)
# print(h)
wb=Workbook("Result.xlsx")
ws=wb.add_worksheet("New Sheet")

first_row=0
for header in ordered_list:
    col=ordered_list.index(header) # we are keeping order.
    ws.write(first_row,col,header) # we have written first row which is the header of worksheet also.

row=1
for _key,_value in temp.items():
    col=ordered_list.index(_key)
    ws.write(row,col,_value)
row+=1 #enter the next row
wb.close()

代码输出

{u'q1_weight': 30.0, u'Items': u'I1', u'q1_normalize': u'', u'q1_value': 21.0, u'Manufacturer': u'M1'}

示例输出

 {u'q1_weight': 30.0, u'Items': u'I1', u'q1_normalize': u'1.42', u'q1_value': 21.0, u'Manufacturer': u'M1'}

0 个答案:

没有答案