简体   繁体   English

将列表元组的列表写入 CSV

[英]Write to CSV a List of Tuples of Lists

I have the following variable:我有以下变量:

data = [(['a', 'b', '3'], ['c', 'a', 'r']),
        (['*', '[', 'e'], ['33', 'gh', 'ew']),
        (['23^', 're#', '4$'], ['tr', 'fF', '5%'])]

I want to write data into a CSV file as follows:我想将data写入 CSV 文件,如下所示:

a c
b a
3 r

* 33
[ gh
e ew

23^ tr
re# fF
4$ 5%

Note that after each iteration I have a black space in between.请注意,在每次迭代之后,我之间都有一个黑色空间。


I tried:我试过了:

import csv 
with open ('train.csv', 'w') as out:
    writer = csv.writer(out)
    for row in dataset:
        writer.writerows(row)

But does not work properly.但不能正常工作。

Since this format doesn't conform to CSV rules you can just use regular string formatting to write the lines.由于此格式不符合 CSV 规则,您可以使用常规字符串格式来编写行。 The one trick is in the handling of the blank line separator.一个技巧是处理空行分隔符。 Assuming you don't want an extra blank line at the bottom of the output file, you can get a bit creative.假设您不想在 output 文件的底部出现额外的空白行,您可以获得一点创意。 Write the separator before writing each group, but start with a blank string and switch it to the real separator after the first write.在写每组之前写下分隔符,但以一个空白字符串开头,并在第一次写后将其切换为真正的分隔符。

data = [(['a', 'b', '3'], ['c', 'a', 'r']),
        (['*', '[', 'e'], ['33', 'gh', 'ew']),
        (['23^', 're#', '4$'], ['tr', 'fF', '5%'])]

with open("test.txt", "w") as file:
    group_sep = "" # group separator written first to avoid extra blank
                   # line at end of file.
    for group1, group2 in data:
        file.write(group_sep)
        group_sep = "\n"
        for cell1, cell2 in zip(group1, group2):
            file.write(f"{cell1} {cell2}\n")

This should get it done.这应该可以完成。

data = [(['a', 'b', '3'], ['c', 'a', 'r']),
        (['*', '[', 'e'], ['33', 'gh', 'ew']),
        (['23^', 're#', '4$'], ['tr', 'fF', '5%'])]


with open('train.txt','w') as f:
    
    for x in  [tuple(zip(x[0],x[1])) for x in data]:
        for r in x:
            f.write(' '.join(r) + '\n')
        f.write('\n')
        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM