gpt4 book ai didi

python - 将列表列表写入 csv 行

转载 作者:行者123 更新时间:2023-12-01 05:38:27 30 4
gpt4 key购买 nike

如何将 list1 或 list2 中的每个列表打印为不包含“[ ]”的列?

import csv
def test():
list1 = [[1, 2, 3, 4], [3, 2, 5], [9, 3, 6, 8, 4]]
list2 = [[2, 2, 4, 4], [1, 9, 10], [2, 7, 7, 4, 5]]
with open('doc.csv', 'w', newline='') as file:
writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(list1)
writer.writerow(list2)
if __name__ == '__main__':
test()

这接近我想要的,但字符串中有 [ ]:

[1, 2, 3, 4],[3, 2, 5],[9, 3, 6, 8, 4]
[2, 2, 4, 4],[1, 9, 10],[2, 7, 7, 4, 5]

编辑:

我想要:

"1, 2, 3, 4","3, 2, 5","9, 3, 6, 8, 4"
"2, 2, 4, 4","1, 9, 10","2, 7, 7, 4, 5"

最佳答案

这就是我要做的:

import csv

def nested_list_formatter(nested):
return tuple(','.join(str(item) for item in sublist) for sublist in nested)

def test():
list1 = [[1, 2, 3, 4], [3, 2, 5], [9, 3, 6, 8, 4]]
list2 = [[2, 2, 4, 4], [1, 9, 10], [2, 7, 7, 4, 5]]
with open('doc.csv', 'w', newline='') as file:
writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(nested_list_formatter(list1))
writer.writerow(nested_list_formatter(list2))

if __name__ == '__main__':
test()

doc.csv的结果内容:

"1,2,3,4","3,2,5","9,3,6,8,4"
"2,2,4,4","1,9,10","2,7,7,4,5"

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

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