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!

1

1 Answer 1

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)] 
Sign up to request clarification or add additional context in comments.

1 Comment

This worked great! I did not know zip() worked that simply. Thanks for the quick answer.

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.