gpt4 book ai didi

python - 如何从python导出不同大小的列表到excel

转载 作者:行者123 更新时间:2023-12-01 04:34:26 24 4
gpt4 key购买 nike

我已经阅读了 Export a Python List to ExcelHow to export user inputs (from python) to excel worksheet ,但不同的是我的列表有不止一种大小。我的意思是我的列表是这样的:

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

list1、list2、...、list10 包含 3 个 float46 格式的数字。例如:

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

...

list10=[3.6565656565465,7.45454536565656,7.56565656565]

我想将列表导出到 Excel 文件,list1 位于第一列,list2 位于第二列,...,list10 位于第十列。

最佳答案

如果您愿意使用 csv 模块写入 csv,然后在 Excel 中打开它,那么您可以将 csv 模块与 一起使用zip() ,将列表列表写为列。示例-

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 个索引,等等。所以这基本上是列表列表的转置。

<小时/>

示例/演示 -

>>> 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 - 如何从python导出不同大小的列表到excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com