我在 Python 中有列表 列表。我希望写个人列表作为xlwt中的一行。
datalist = [['India', 'Yes', '99%'], [['China', 'Yes', '89%'], ['Brazil', 'No', '90%']], ['Russia', 'Yes', '92%'], [['Germany', 'No', '97%'], ['Spain', 'No', '70%']]]
首先,我计算了列表 def计数(local_list)的总数:
def listcount(lst):
listsum = 0
for item in lst:
if not isinstance(l,list):
return 1
else:
listsum+= listcount(item)
return listsum
excel_export.py
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet("PySheet1")
for rownum in range(listcount(datalist)):
row = sheet.row(rownum)
for index, col in enumerate(datalist):
# do something similar like in listcount()
# check if instance is list if not then write the value
# rownum will act as a row
# column value will come from list item
row.write(row, col, val)
book.save("test.xls")
Samplesheet
如何在适当的行和列中编写列表值?
答案 0 :(得分:1)
从一开始就一劳永逸地处理列表的奇怪结构要简单得多:
datalist = [['India', 'Yes', '99%'], [['China', 'Yes', '89%'], ['Brazil', 'No', '90%']], ['Russia', 'Yes', '92%'],
[['Germany', 'No', '97%'], ['Spain', 'No', '70%']]]
new_datalist = []
for lst in datalist:
if isinstance(lst[0], list):
new_datalist.extend(lst)
else:
new_datalist.append(lst)
datalist = new_datalist
print(datalist)
输出:
[['India', 'Yes', '99%'], ['China', 'Yes', '89%'], ['Brazil', 'No', '90%'], ['Russia', 'Yes', '92%'], ['Germany', 'No', '97%'], ['Spain', 'No', '70%']]
现在,您可以直接将值写入工作表。你也可以摆脱listcount
。