如何将大小不同的列表从python导出到excel [英] How to export a list with different size from python to excel

查看:307
本文介绍了如何将大小不同的列表从python导出到excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了将Python列表导出到Excel 如何将用户输入(从python)导出到Excel工作表,但不同之处在于我的列表大小不只一种.我的意思是我的清单是这样的:

I already read Export a Python List to Excel and How to export user inputs (from python) to excel worksheet, but the different is that my list is in more than one size. I mean my list is something like this:

List=[[list1],[list2],...,[list10]]

list1,list2,...,list10包含3个数字,具有float46格式.例如:

list1, list2,...,list10 are including of 3 numbers with float46 formats. For example:

list1=[1.34543324545676,2.4354356645454,2.786434355455]
list2=[3.33434342343423,6.6566665655655,7.343545454545]

...

list10=[3.6565656565465,7.45454536565656,7.56565656565]

我想将列表导出到第一列中 list1 ,第二列中 list2 ..., list10的Excel文件在第十列中.

I want to export the List to an Excel file that list1 is in the first column, list2 is in the second column, ..., list10 is in the tenth column.

推荐答案

如果可以使用csv模块写入csv,然后在excel中将其打开,则可以使用csv模块使用zip(),将您的列表列表写为列.示例-

If you are fine with using csv module to write to a csv, and then open it up in excel, then you can use csv module along with zip() , to write out your list of lists as columns. Example -

import csv
with open('<excel file>','w') as f:
    writer = csv.writer(f)
    #writer.writerow([<header row>]) #uncomment this and put header, if you want header row , if not leave it commented.
    for x in zip(*list_of_lists):
        writer.writerow(x)

*list_of_list解压缩列表并将每个内部列表作为单独的参数发送给zip(),并且zip()在每个索引处组合每个列表,因此zip()的第一个列表输出是所有列表的第0个索引,依此类推因此,这基本上是对列表列表进行转置.

The *list_of_list unpacks the lists and sends each inner list as a separate argument to zip() and zip() combines each list at each index so first list output of zip() is the 0th index of all lists, etc. So this basically transposes the list of lists.

示例/演示-

>>> import csv
>>> ll = [[1,2,3],[3,4,5],[4,2,1]]
>>> with open('a.csv','w') as f:
...     writer = csv.writer(f)
...     for x in zip(*ll):
...         writer.writerow(x)
...

a.csv中的输出为-

1,3,4

2,4,2

3,5,1


我认为,如果需要,也可以对其他excel库执行类似的操作(使用zip()).

这篇关于如何将大小不同的列表从python导出到excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆