【问题标题】:Write a list of lists into csv in Python [duplicate]在Python中将列表列表写入csv [重复]
【发布时间】:2019-06-22 06:47:29
【问题描述】:

我有一个像这样的纯数据列表

a=[[1,2,3],
   [4,5,6],
   [7,8,9]]

如何将a 写入 CSV 文件,每个列表都在这样的列中?

1 4 7 
2 5 8
3 6 9

【问题讨论】:

  • 转置你的DataFrame a=[[1,2,3],[4,5,6],[7,8,9]]; df = pd.DataFrame(a).T; df.to_csv("output.csv",index=False,header=False)

标签: python list file csv


【解决方案1】:

用途:

import csv
with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(list(zip(*l)))

【讨论】:

    【解决方案2】:

    试试这个:

    import csv
    with open('output.csv', 'w', newline='') as f:
        writer = csv.writer(f, delimiter=' ')
        writer.writerows(a)
    

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 2023-03-17
      • 2016-07-11
      • 2018-02-03
      • 2018-11-22
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      相关资源
      最近更新 更多