我有一个电子表格,我使用xlrd解析为python。
我需要将它(包括其他表格)纠缠在一个像这样的词典列表中:
[{"price4-0": 18.22, "price4-1": 21.23, "price4-4": 25.65, "quantity": 100.0, "turnaround": "1days", "size": "2 x 2"},
{"price4-0": 16.44, "price4-1": 19.43, "price4-4": 23.54, "quantity": 200.0, "turnaround": "1days", "size": "2 x 2"}...]
所以'周转'字典值取自工作表名称,而另一个字典键是第一行值。我正在尝试写它,所以如果添加另一个工作表或另一行,它仍然可以工作。基本上循环并在正确的位置添加正确的值。我有一个硬编码版本,它给出了正确的结果,但它需要是动态的:
from pprint import pprint
import xlrd
wb = xlrd.open_workbook('cardprice.xls')
pricelist = []
for i, x in enumerate(wb.sheets()):
for r in range(x.nrows)[1:]:
row_values = x.row_values(r)
pricelist.append({'turnaround':x.name,
'size':row_values[0],
'quantity':row_values[1],
'price4-0':row_values[2],
'price4-1':row_values[3],
'price4-4':row_values[4]
})
pprint(pricelist)
答案 0 :(得分:2)
pricelist = []
for i, x in enumerate(wb.sheets()):
header_cells = x.row(0)
num_rows = x.nrows - 1
curr_row = 0
header = [each.value for each in header_cells]
while curr_row < num_rows:
curr_row += 1
row = [int(each.value)
if isinstance(each.value, float)
else each.value
for each in work_sheet.row(curr_row)]
value_dict = dict(zip(header, row))
value_dict['turnarround'] = x.name
pricelist.append(value_dict)
print(pricelist)