gpt4 book ai didi

python - 将列表放入 csv

转载 作者:行者123 更新时间:2023-12-01 07:36:40 24 4
gpt4 key购买 nike

我有一个 Python 3 列表。我想将列表 [1,2,3,4,5,6,7,8] 拆分为一行中的 [1,2,3,4] 和 [5 ,6,7,8]其他。我目前正在使用它写入 CSV,但是我正在手动进行分割,写入后会有一个空白单元格,不知道如何摆脱它,这也是另一个问题

outfile = open('list.csv','w')
out = csv.writer(outfile)
out.writerows(map(lambda x: [x],list))
outfile.close()

最佳答案

试试这个:

outfile = open('list.csv', 'w', newline='')
out = csv.writer(outfile)
out.writerows([list[i:i+4] for i in range(0, len(list), 4)])
outfile.close()

或者使用with open:

with open('list.csv', 'w', newline='') as outfile:
out = csv.writer(outfile)
out.writerows([list[i:i+4] for i in range(0, len(list), 4)])

关于python - 将列表放入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com