Search code examples
pythonlistcsv

convert a list of lists into a vertical string


So I wanted to open a CSV file, sort it, and then create a new file and place the sorted values into a new CSV file. I managed to get through the first two steps, but placing the CSV file back into a new file is what I'm having trouble with.

 g = open(FOUT,'w')
 newcsv = sorted(accum, key = sortKey)
 g.write(''.join('\n'.join(map((lambda x: str(x), newcsv)))))
 g.close()

This works only partially because my newcsv is actually a list of list, meaning I get an output of

[3.0, 12.0, 11.0, 17.0]
[5.0, 6.0, 17.0, 30.0]
[1.0, 10.0, 100.0, -40.0]

What I want is:

3.0, 12.0, 11.0, 17.0
5.0, 6.0, 17.0, 30.0
1.0, 10.0, 100.0, -40.0

Any way of doing this? just removing the lists?

Thanks!


Solution

  • You need to invert the order of the join

    In [22]: l = [[3.0, 12.0, 11.0, 17.0],
        ...: [5.0, 6.0, 17.0, 30.0],
        ...: [1.0, 10.0, 100.0, -40.0]]
    
    In [23]: l = [",".join(map(lambda x: str(x),i)) for i in l]
    
    In [24]: l 
    Out[24]: ['3.0,12.0,11.0,17.0', '5.0,6.0,17.0,30.0', '1.0,10.0,100.0,-40.0']
    
    In [25]: '\n'.join(l) 
    Out[25]: '3.0,12.0,11.0,17.0\n5.0,6.0,17.0,30.0\n1.0,10.0,100.0,-40.0'
    

    So, your code will look like this:

    g = open(FOUT,'w')
    newcsv = sorted(accum, key = sortKey)
    g.write('\n'.join([",".join(map(lambda x: str(x),i)) for i in newcsv])
    g.close()
    

    You can also refactor to map(str,i), and map will take care of calling str on each element of the list i

    g = open(FOUT,'w')
    newcsv = sorted(accum, key = sortKey)
    g.write('\n'.join([",".join(map(str,i)) for i in newcsv])
    g.close()