0

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:

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?

3 Answers 3

3

To write out the data to CSV, simply use the csv module and give it one row; 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
Sign up to request clarification or add additional context in comments.

Comments

2

Disclaimer - Not very efficient Python code.

But, it does the job. (You can adjust the width (currently 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. I really want to improve this one.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.