Hi, everyone, I am a newbie for the python, right now I am doing a small program to read and write the xlsx file. I have refered some codes, and it is seems like I have some problems to deal with the data in this program.
我想求教一下,关于数据嵌套的问题,我是新手
# -*- coding: utf-8 -*-
import xdrlib,sys
import xlrd
import xlwt
def open_excel(file= 'incomingtry.xlsx'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
def excel_table_byindex(file= 'incomingtry.xlsx',colnameindex=0,by_index=0):
data = open_excel(file)
table = data.sheets()[by_index]
nrows = table.nrows
ncols = table.ncols
colnames = table.row_values(colnameindex)
list =[]
for rownum in range(1,nrows):
row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
def excel_table_byname(file='incomingtry.xlsx',colnameindex=0,by_name=u'Sheet1'):
data = open_excel(file)
table = data.sheet_by_name(by_name)
nrows = table.nrows
colnames = table.row_values(colnameindex)
list =[]
for rownum in range(1,nrows):
row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
def creat_the_newfile():
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
def main():
tables = excel_table_byindex()
#print tables
for row in tables:
print row
#print "%d",row['order'];
#for i in range(len(tables)):
# print row{i}
print 'I have',len(tables)
print 'The 3rd row ist',tables[2]
Total_rownum=len(row)
print 'The lenght of row ist',Total_rownum
if __name__=="__main__":
main()
我看到了,这个tables是个list,而row则是dict,正确么?现在我如何访问或者操作list tables中row的每一个元素呢?
谢谢帮助
for this code, in the final step, I noticed that the tables is a list, but the row is dict embeded in the tables, so my question is, how can I visit the elements in all row and operate them?
thanks for your helping!
搞不清楚你要问什么?dict就用dict的函数
想针对整个list操作可以用numpy/pandas,一维是列表,二维是字典,用pandas更方便,但估计你暂时还没能力学这个,先搞清dict吧