Python 3.x Python CSV-在同一CSV文件中写入不同的列表

Python 3.x Python CSV-在同一CSV文件中写入不同的列表,python-3.x,csv,Python 3.x,Csv,请参见下面的更新 对于我的Python程序,我需要将3个不同的列表写入csv文件,每个列表位于不同的列中。每个列表都有不同的大小 l1 = ['1', '2', '3', '4', '5'] l2 = ['11', '22', '33', '44'] l3 = ['111', '222', '333'] f = 'test.csv' outputFile = open(f, 'w', newline='') outputWriter = csv.writer(resultFile, delimi

请参见下面的更新

对于我的Python程序,我需要将3个不同的列表写入csv文件,每个列表位于不同的列中。每个列表都有不同的大小

l1 = ['1', '2', '3', '4', '5']
l2 = ['11', '22', '33', '44']
l3 = ['111', '222', '333']
f = 'test.csv'
outputFile = open(f, 'w', newline='')
outputWriter = csv.writer(resultFile, delimiter=';')
outputWriter.writerow(headerNames)
for r in l3:
    resultFile.write(';' + ';' + r + '\n')
for r in l2:
    resultFile.write(';' + r + '\n')
for r in l1:
    resultFile.write(r + '\n')
resultFile.close()
不幸的是,这不起作用。列表的值写在右侧列中每个列表的下面。我更喜欢将列表值并排书写,如下所示:

1;11;111
2;22;222
etc.
我相信有一个简单的方法可以做到这一点,但经过几个小时的尝试,我仍然无法找到它

更新:

我尝试了以下方法。这是一个进步,但我还没有做到

f = input('filename: ')
l1 = ['1', '2', '3', '4', '5']
l2 = ['11', '22', '33', '44']
l3 = ['111', '222', '333']
headerNames = ['Name1', 'Name2', 'Name3']
rows = zip(l1, l2, l3)
with open(f, 'w', newline='') as resultFile:
    resultWriter = csv.writer(resultFile, delimiter=';')
    resultWriter.writerow(headerNames)
    for row in rows:
        resultWriter.writerow(row)

它以我想要的格式写入数据,但是没有写入值4、5和44

您的第一次尝试没有正确使用csv模块,也没有像第二次尝试那样转换行

现在,当最短的行结束时,压缩行将立即停止。您需要的是
itertools.ziplongest
(例如,填充值为0)

输出文件包含:

Name1;Name2;Name3
1;11;111
2;22;222
3;33;333
4;44;0
5;0;0

谢谢你的意见!由于列表的长度不同,因此不会写入值4、5和44。你有解决这个问题的办法吗?@WesselJespers请看我的编辑。我想这正是您现在想要的查看
itertools.zip\u longest
Name1;Name2;Name3
1;11;111
2;22;222
3;33;333
4;44;0
5;0;0