Python 打印使用xlrd从excel创建的字典的键和值
这段代码的输出结果是Python 打印使用xlrd从excel创建的字典的键和值,python,excel,dictionary,printing,xlrd,Python,Excel,Dictionary,Printing,Xlrd,这段代码的输出结果是 import xlrd import os wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls")) sheet = wb.sheet_by_name('Sheet1') sheetdict = {} #build ductionary3 for rownum in range(sheet.nrows): sheetdict[
import xlrd
import os
wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls"))
sheet = wb.sheet_by_name('Sheet1')
sheetdict = {}
#build ductionary3
for rownum in range(sheet.nrows):
sheetdict[sheet.cell(rownum,0)] = [sheet.cell(rownum,1)]
#test print dictionary in format: Co-60 - 16 Ci
for keys,values in sheetdict.items():
print(keys,values)
等等
我不知道文本:和[number:\ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u \ u。我认为它们实际上是从excel中存储在字典中的数据的一部分,但我不知道如何删除它,也不知道excel正在做什么导致了它
我对Python(一般来说是编码)非常陌生,因此非常感谢所有帮助 在
xlrd
中调用工作表
对象的单元格
方法实际上返回一个单元格
对象。此单元格
对象与您正在查找的值不完全相同。如果需要值本身,则需要使用单元格
对象的.value
属性来访问它。总之,您不需要使用sheetdict[sheet.cell(rownum,0)]=[sheet.cell(rownum,1)]
,而需要使用sheetdict[sheet.cell(rownum,0.value)]=[sheet.cell(rownum,1.value]
专门访问cell
对象的.value
属性
因此,您的脚本应该是:
text:'AC225' [number:0.16]
text:'AC227' [number:0.0024]
text:'AC228' [number:14.0]
text:'AG105' [number:54.0]
text:'AG108M' [number:19.0]
text:'AG110M' [number:11.0]
此外,为了避免必须处理单元格
对象,您可以使用工作表
对象的.col\u values
方法直接访问您正在处理的两列(0和1)中的每一列的值。这将生成两个值列表,您可以一起zip
,并将其转换为字典
。以下是上述脚本的调整版本:
import xlrd
import os
wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls"))
sheet = wb.sheet_by_name('Sheet1')
sheetdict = {}
#build ductionary3
for rownum in range(sheet.nrows):
sheetdict[sheet.cell(rownum,0).value] = [sheet.cell(rownum,1).value]
#test print dictionary in format: Co-60 - 16 Ci
for keys,values in sheetdict.items():
print(keys,values)
我希望这有帮助
import xlrd
import os
wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls"))
sheet = wb.sheet_by_name('Sheet1')
# get column values, zip them together and convert the output into a dictionary
sheetdict = dict(zip(*[sheet.col_values(i) for i in range(2)]))
for keys,values in sheetdict.items():
print(keys,values)