0

I have a long list of lists of the following form ---

a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

and it is easily achieve by this code:

You could use pandas:

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

But i want in this Format:

1.2 1.2 . . . 1.4
abc wer . . . qew
3   4   . . . 2
  • Is each column left-aligned in the file, padded on the right with spaces? Is there one space between each column? Does your file have just three lines of long length? Your two example results differ from each other. Please explain "this Format" further. – Rory Daulton Mar 25 '17 at 19:51

1 Answers1

0

Try this. Just a proof of concept, but you can probably wrap this in to whatever you need:

a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

# Rotate
rotated = zip(*a)

# Find the longest string of each set
max_lengths = [ max([ len(str(value)) for value in l ]) for l in a ]

# Generate lines
lines = []
for values in rotated:
    items = []
    for i, value in enumerate(values):
        value_str = str(value)
        if len(value_str) < max_lengths[i]:
            # Add appropriate padding to string
            value_str += " " * (max_lengths[i] - len(value_str))
        items.append(value_str)
    lines.append(" ".join(items))

print "\n".join(lines)

Which outputs:

1.2 1.2   1.4
abc werew qew
3   4     2
Julien
  • 5,243
  • 4
  • 34
  • 35