我有三个列表,其中一个嵌套如下:
a = [1, 2, 3, 4]
b = ["abc", "def", "dec", "erf"]
c = [[5, 6, 7], [8, 9, 10], [11, 12, 13.3], [14, 15, 16]]
我想要一个CSV
文件输出,看起来像这样:
1,abc,5,6,7
2,def,8,9,10
3,erf,11,12,13.3
...
我尝试将它们压缩并写入CSV
文件,如下所示:
with open('filer.csv', "w") as f:
writer = csv.writer(f)
for row in zip(a, b, c):
writer.writerow(row)
但是输出有这些愚蠢的括号,像这样:
1,abc,"[5,6,7]"
2,def,"[8,9,10]"
3,erf,"[11,12,13.3]"
...
但是我希望它们没有括号和引号,像这样:
1,abc,5,6,7
2,def,8,9,10
3,erf,11,12,13.3
...
:
使用说明:
with open('filer.csv', "w") as f:
writer = csv.writer(f)
for ai, bi, ci in zip(a, b, c):
writer.writerow([ai, bi, *ci])
1,abc,5,6,7
2,def,8,9,10
3,dec,11,12,13.3
4,erf,14,15,16
正如您所说的,您有嵌套列表,所以您需要将列表平化,表达式[ai, bi, *ci]
将其平化。
您得到括号的原因是writerow
(可能)对传递给它的可迭代对象的每个元素应用函数str。列表的字符串表示形式包括括号,例如:
In[3]: str([1, 2, 3])
Out[3]: '[1, 2, 3]'