简体   繁体   English

如何将元组列表转换为不同的csv文件

[英]How to convert a list of tuples into different csv files

I have a list of tuples like this: 我有一个这样的元组列表:

List=[ ('1',['45','55','56','57']) , ('2',['200','202','202']) , ('3',['500','501','502'])]

As can be seen, three tuples of size 2. 可以看出,大小为2的三个元组。

I want to convert this list into three different csv files. 我想将此列表转换为三个不同的csv文件。

The output should be three different csv file with the names of "1.csv","2.csv","3.csv" 输出应该是三个不同的csv文件,其名称分别为“ 1.csv”,“ 2.csv”,“ 3.csv”

While the files you want are valid CSV files, they're so trivial there's no need to use the csv module to create them (or read them). 虽然所需的文件是有效的CSV文件,但它们是如此琐碎,因此无需使用csv模块来创建它们(或读取它们)。

data = [
    ('1', ['45', '55', '56', '57']),
    ('2', ['200', '202', '202']),
    ('3', ['500', '501', '502']),
    ]

for dataset_name, dataset in data:
    with open('{}.csv'.format(dataset_name), 'w') as outfile:
        for item in dataset:
            outfile.write('{}\n'.format(item))

This assumes each item in the lists should be on their own line. 假定列表中的每个项目都应在各自的行上。

If you want the data in one row: 如果要将数据放在一行中:

List=[ ('1',['45','55','56','57']) , ('2',['200','202','202']) , ('3',['500','501','502'])]

for filename, data in List:
    with open('{}.csv'.format(filename), 'w') as f_output:
        f_output.write(','.join(data))

This would give you: 这将为您提供:

1.csv 1.csv

45,55,56,57

2.csv 2.csv

200,202,202

3.csv 3.csv

500,501,502

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

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