用标题列出到python中的csv

我编写了一个脚本,它将下面的列表作为输出.

['red', '361', '0']
['blue', '1', '0']
['orange', '77', '0']
['cream', '660', '73']
['ivory', '159', '0']

这个列表非常庞大,我想将输出内容写入带有标题的csv,如下所示.

color | total | fail

以下是我试图实现它的方式

with open('colour.csv', 'wb') as csvfile:
    header = ['color', 'total', 'fail']
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(header)
    for row in output:
        writer.writerow(output)

但我得到的输出并不像预期的那样.生成csv并将列表的最后一行打印三次到csv.我无法找到为什么不打印所有其他行或为什么最后一行打印三次?
这是我得到的示例输出:

color | total | fail
ivory | 159 | 0
ivory | 159 | 0
ivory | 159 | 0

这就是我期望输出的结果:

color | total | fail
red | 361 | 0 
blue | 1 | 0
orange | 77 | 0
cream | 660 | 73
ivory | 159 | 0

有人可以帮我这个吗?

最佳答案 代码 –

import csv

arr = [['red', '361', '0'],
      ['blue', '1', '0'],
      ['orange', '77', '0'],
      ['cream', '660', '73'],
      ['ivory', '159', '0']]

with open('output.csv','w') as f:
    writer = csv.writer(f)
    writer.writerow(['color', 'total', 'fail'])
    writer.writerows(arr)
点赞