繁体   English   中英

需要通过python输出的csv的帮助

[英]Need help on csv output via python

好的,所以我有3个数据列表。 每个都有不同的长度,彼此之间没有关联。

我遇到的问题是,当我去写bList时,它会写到aList完成后的行中。 所以它们都在正确的列中,这很花哨,但我只希望每列都从第2行开始(第1行保留用于标题)。 相反,我的aList从第1行开始,在第28行结束,然后bList从29开始,依此类推。

这就是我所拥有的,我希望你们中的一位向导会解释如何解决。 我了解导致问题的原因,但我不知道如何解决。

def write_output(file):
    f = open(file, 'w')
    fields = ('a', 'b', 'c')
    wr = csv.DictWriter(f, delimiter=",", fieldnames=fields, lineterminator = '\n')

    wr.writeheader()
    for row in aList:
        wr.writerow({'a':row})
    for row in bList:
        wr.writerow({'b':row})
    for row in cList:
        wr.writerow({'c':row})

使用zip_longest。

如果您的列表不包含None值的示例:

from itertools import zip_longest

for a_b_c in zip_longest(aList, bList, cList):
    row = {k: v for k, v in zip(fields, a_b_c) if v is not None}
    wr.writerow(row)

这是一个功能全面的示例。

该脚本不使用任何库,可以在Python 2.7运行。 您只需确保每个值都用逗号定界,就可以创建CSV(逗号分隔值)文件。 另外,我使用map函数代替了itertools

# Python 2.7    
# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]

# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')

# Adds headers in the first row
output_file.write('aList,bList,cList\n')

# Adds all the elements from the lists, row-by-row
for a, b, c in map(None, aList, bList, cList):
    output_file.write('%s,%s,%s\n' % (a, b, c))

# Closes your file
output_file.close()

Python 3map函数不再支持None作为映射函数。 在这种情况下, itertools库中的zip_longest函数可能是最干净的方法(请注意,在Python 2.7itertools此函数称为izip_longest

# Python 3.x
import itertools

# Here is an example of three lists of different lengths
aList = [9,8,2,5,14,6]
bList = [8,7,5,4]
cList = [9,15,25,60,47,88,3]

# Creates your empty CSV file
output_file = open(r'C:\Temp\output.csv', 'w')

# Adds headers in the first row
output_file.write('aList,bList,cList\n')

# Adds all the elements from the lists, row-by-row
for a, b, c in itertools.zip_longest(aList, bList, cList):
    output_file.write('%s,%s,%s\n' % (a, b, c))

# Closes your file
output_file.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM