2

My list is generated dynamically each time, but for this example the list can be a basic range of 0 - 24. The list is split by my function and written to a CSV file. Here is a bit of the code:

numSeq = range(25)

def split_list(alist, rows):
    length = len(alist)
    return [alist [i*length // rows: (i+1)*length // rows] for i in range(rows)]

with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(split_list(numSeq, 5))

This pretty much works fine. The problem is, I want to split it into columns not rows. Specifically, it is writing to the CSV like this:

00,01,02,03,04
05,06,07,08,09
10,11,12,13,14
15,16,17,18,19
20,21,22,23,24

However, I need it to split & write like this:

00,05,10,15,20
01,06,11,16,21
02,07,12,17,22
03,08,13,18,23
04,09,14,19,24

Any idea on how I could go about doing this? Thanks in advance!

Sorry for poor formatting, I'm on mobile!

dimensive
  • 205
  • 2
  • 3
  • 5

1 Answers1

4

You can transpose the resulting list using zip() function:

writer.writerows(zip(*split_list(numSeq, 5)))

Example:

>>> lst = [[1, 2, 3], [4, 5, 6]]
>>> zip(*lst)
[(1, 4), (2, 5), (3, 6)] 
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119