简体   繁体   English

将具有嵌套元组的列表写入CSV文件

[英]Writing a list with nested tuples to a csv file

I have a list with nested tuples, like the one below: 我有一个包含嵌套元组的列表,如下所示:

data = [('apple', 19.0, ['gala', '14', 'fuji', '5', 'dawn', '3', 'taylor', '3']),
 ('pear', 35.0, ['anjou', '29', 'william', '6', 'concorde', '4'])]

I want to flatten it out so that I can write a .csv file in which each item on every list corresponds to a column: 我想将其展平,以便我可以编写一个.csv文件,其中每个列表上的每个项目都对应于一列:

apple    19.0,   gala   14   fuji    5 dawn     3 taylor 3
pear     35.0    anjou  29   william 6 concorde 4

I tried using simple flattening: 我尝试使用简单的展平:

flattened = [value for pair in data for value in pair]

But the outcome has not been the desired one. 但是结果并不是想要的。 Any ideas on how to solve this? 关于如何解决这个问题的任何想法?

To write out the data to CSV, simply use the csv module and give it one row; 要将数据写到CSV,只需使用csv模块并将其排成一行; constructing the row is not that hard: 构造行并不难:

import csv

with open(outputfile, 'w', newlines='') as ofh:
    writer = csv.writer(ofh)

    for row in data:
        row = list(row[:2]) + row[2]
        writer.writerow(row)

This produces: 这将产生:

apple,19.0,gala,14,fuji,5,dawn,3,taylor,3
pear,35.0,anjou,29,william,6,concorde,4

Disclaimer - Not very efficient Python code. 免责声明-效率不高的Python代码。

But, it does the job. 但是,它可以完成工作。 (You can adjust the width (currently 10)) (您可以调整宽度(当前为10))

data = [('apple', 19.0, ['gala', '14', 'fuji', '5', 'dawn', '3', 'taylor', '3']),
        ('pear', 35.0, ['anjou', '29', 'william', '6', 'concorde', '4'])]

flattened = list()
for i, each in enumerate(data):
    flattened.append(list())
    for item in each:
        if isinstance(item, list):
            flattened[i].extend(item)
        else:
            flattened[i].append(item)
# Now print the flattened list in the required prettified manner.
for each in flattened:
    print ("".join(["{:<10}".format(item) for item in each]))
    # String is formatted such that all items are width 10 & left-aligned

Note - I tried to write the function for a more general case. 注意-我试图为更一般的情况编写函数。
PS - Any code suggestions are welcome. PS-欢迎提供任何代码建议。 I really want to improve this one. 我真的很想改善这一点。

This seems like it calls for recursion 这似乎需要递归

def flatten(inlist):
    outlist=[]
    if isinstance(inlist, (list, tuple)):
        for item in inlist:
            outlist+=flatten(item)
    else:
        outlist+=[inlist]
    return outlist

This should work no matter how nested your list becomes. 无论列表如何嵌套,这都应该起作用。 Tested it with this: 对此进行了测试:

>>> flatten([0,1,2,[3,4,[5,6],[7,8]]])
[0, 1, 2, 3, 4, 5, 6, 7, 8]

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

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