使用dict python中的值创建excel文件

2024-03-28 12:48:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个下面给出的代码,我想用它来创建一个excel文件。文件代码为:

#!/usr/bin/python
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
orf = {1: ('793', 804, 12, 0), 2: ('952', 1020, 69, 0), 3: ('1222', 1227, 6, 0), 4: ('1309', 1338, 30, 0), 5: ('1921', 1977, 57, 0), 6: ('2164', 2253, 90, 0), 7: ('2305', 2337, 33, 0)}
ws.write(0, 0, "NO.")
ws.write(0, 1, "Direction")
ws.write(0, 2, "Frame")
ws.write(0, 3, "Start")
ws.write(0, 4, "End")
ws.write(0, 5, "Codon numbers")
ws.write(0, 6, "ORF Sequence")

j = 1
k = 2
for i in orf.items():
    numorf=i[0]
    startorf=orf[numorf][0]
    stoporf=orf[numorf][1]
    lengthorf=orf[numorf][2]
    frameorf=orf[numorf][3]        
    ws.write(j, k, numorf)
    ws.write(j, k, "5 to 3")
    ws.write(j, k, frameorf)
    ws.write(j, k, startorf)  
    ws.write(j, k, stoporf)
    ws.write(j, k, lengthorf)
    ws.write(j, k, "ATGACA...ATGCGA")
    j = j+1
    k = k+1   


wb.save('example.xls')

代码的所有部分工作正常,但循环中的部分编写字典值不正确,并出现以下错误

for i,j,k in orf.items():
ValueError: need more than 2 values to unpack

我试图解决它,但没有成功。你知道吗

如何在循环中正确管理列和行号,以便使用dict中的值创建文件?你知道吗

为了弄清楚,我想把numorf的值放在“NO.”下面,“5到3”放在“direction”下面,“frameorf”放在“Frame”下面,“startorf”放在“Start”下面,“stoporf”放在“End”下面,“lenghtorf”放在“Codon numbers”下面,“ATGACA…ATGCGA”放在“ORF Sequence”下面。你知道吗


Tags: 文件no代码wsframestartwriteend
1条回答
网友
1楼 · 发布于 2024-03-28 12:48:02

首先,代码片段中的forint与错误片段中的不同。你知道吗

不管怎样,我认为你想要的是:

for row,values in orf.iteritems():
    startorf,stoporf,lengthorf,frameorf = values
    ws.write(row, 0, row)
    ws.write(row, 1, "5 to 3")
    ws.write(row, 2, frameorf)
    ws.write(row, 3, startorf)  
    ws.write(row, 4, stoporf)
    ws.write(row, 5, lengthorf)
    ws.write(row, 6, "ATGACA...ATGCGA")

前2行也可以重写为:

for row,(startorf,stoporf,lengthorf,frameorf) in orf.iteritems(): 
    # note the parenthesis, them make the tuple (the value) expand in the respective variables
    # just write to the worksheet as before
    ws.write(row, 0, row) 
    # ...

相关问题 更多 >