将 Python 列表写入 csv 中的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17704244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:57:15  来源:igfitidea点击:

Writing Python lists to columns in csv

pythonlistcsv

提问by Alex Chumbley

I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

我有 5 个列表,长度都相同,我想将它们写入 CSV 中的 5 列。到目前为止,我只能使用以下代码向一列写入一个:

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in test_list:
        writer.writerow([val])

If I add another forloop, it just writes that list to the same column. Anyone know a good way to get five separate columns?

如果我添加另一个for循环,它只会将该列表写入同一列。有人知道获得五个单独列的好方法吗?

采纳答案by Joran Beasley

change them to rows

将它们更改为行

rows = zip(list1,list2,list3,list4,list5)

then just

那么就

import csv

with open(newfilePath, "w") as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

回答by jh314

You can use izipto combine your lists, and then iterate them

您可以使用izip组合您的列表,然后迭代它们

for val in itertools.izip(l1,l2,l3,l4,l5):
    writer.writerow(val)

回答by Ashok Kumar Jayaraman

The following code writes python lists into columns in csv

以下代码将python列表写入csv中的列

import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
      wr = csv.writer(myfile)
      wr.writerow(("List1", "List2"))
      wr.writerows(export_data)
myfile.close()

The output looks like this

输出看起来像这样

enter image description here

在此处输入图片说明

回答by Shb8086

import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w") 
for key in dic.keys():
    row ="\n"+ str(key) + "," + str(dic[key]) 
    csv.write(row)

回答by jpp

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

如果您乐于使用 3rd 方库,您可以使用 Pandas 来实现。好处包括无缝访问专用方法和行/列标签:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

回答by Bartats

I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:

我不想导入 csv 以外的任何东西,而且我所有的列表都有相同数量的项目。这里的最佳答案似乎是将列表每行分成一行,而不是每列一列。因此,我在这里接受了答案并提出了这个:

import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(("list1", "list2"))
    rcount = 0
    for row in list1:
        wr.writerow((list1[rcount], list2[rcount]))
        rcount = rcount + 1
    myfile.close()

回答by BinaryPhinary

I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.

我只是想添加到这个 - 因为坦率地说,我用头撞了一段时间 - 虽然对 python 非常陌生 - 也许它会帮助其他人。

 writer.writerow(("ColName1", "ColName2", "ColName"))
                 for i in range(len(first_col_list)):
                     writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))