[英]How to write nested list to excel in python?
I have a nested list like:我有一个嵌套列表,如:
lst = [['Fruit'], [1,2,3,4], [{'name':'banana', 'count': 3, 'color':'red'}, {'name':'apple', 'count': 12, 'color':'green'}]]
and I want to write this list to an excel file (.xlsx).我想将此列表写入 excel 文件 (.xlsx)。 My expected result is:
我的预期结果是:
workbook = xlsxwriter.Workbook('lst.xlsx')
worksheet = workbook.add_worksheet()
lst = [['Fruit'], [1,2,3,4], [{'name':'banana', 'count': 3, 'color':'red'}, {'name':'apple', 'count': 12, 'color':'green'}]]
for i, l in enumerate(lst):
for j, col in enumerate(l):
worksheet.write(i, j, col)
workbook.close()
but it gives an error: TypeError: Unsupported type <class 'dict'> in write()
但它给出了一个错误:
TypeError: Unsupported type <class 'dict'> in write()
Try converting the elements into string before writing into the Excel sheet在写入 Excel 工作表之前尝试将元素转换为字符串
for i, l in enumerate(lst):
for j, col in enumerate(l):
worksheet.write(i, j, str(col))
I finally solved the problem with:我终于解决了这个问题:
for i in range(0, len(lst)):
worksheet.write(0, i, ','.join([str(elem) for elem in lst[i]]))
Cleanest way to do so would be to use pandas:最干净的方法是使用熊猫:
import pandas as pd
pd.DataFrame([lst]).to_excel('excel_file.xlsx')
You're using
Nested Loop
for entering your data into Excel File , So, you need to care about your data algorithm of what you're entering in case ofindex()
您正在使用
Nested Loop
将数据输入Excel File ,因此,您需要关心您在index()
情况下输入的数据算法
Algorithm算法
You need To care about the indexing position of your data, so what we gonna do is explain how the data is entered;你需要关心你的数据的索引位置,所以我们要做的就是解释数据是如何输入的;
we want it to look like this:我们希望它看起来像这样:
i j lista
0 0 fruit
0 1 (1, 2, 3, 4, 5)
0 2 {'name': 'banana', 'count': 3}
In python, It should looks like this,在python中,它应该是这样的,
# I've a List of lists called `lista`:-
lista = [['Fruit'], [(1,2,3,4)], [{'name':'banana', 'count': 3, 'color':'red'}, {'name':'apple', 'count': 12, 'color':'green'}]
# By using `Nested Loop`, we can specify the entrance of the data of `lista`
for i in range(1): # Specify any range you want
for j in range(0, len(lista)):
print(i, j, list[j][i])
workbook = xlsxwriter.Workbook('lst.xlsx')
worksheet = workbook.add_worksheet()
# First, to add the sec `index`, you need to add it into a `tuple`
lst = [['Fruit'], [(1,2,3,4]), [{'name':'banana', 'count': 3, 'color':'red'}, {'name':'apple', 'count': 12, 'color':'green'}]]
for i in range(1): # Specify any range you want
for j in range(0, len(lista)):
worksheet.write(i, j, lista[j][i])
workbook.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.