Turn multiple lists into one list in python

Question:

I have a spreadsheet with data which I have imported into python using the following code;

import xlrd

wb = xlrd.open_workbook('data.xls')

sh = wb.sheet_by_index(0)

for rownum in range(sh.nrows):
    print sh.row_values(rownum)

This prints out each row of the spreadsheet; eg.

[13.0, 2.0, 92.0, 83.0]
[10.0, 8.0, 80.0, 78.0]
[7.0, 4.0, 121.0, 60.0]

How do I grab these separate lists and merge them into one list that would look like;

test = [[13.0, 2.0, 92.0, 83.0], [10.0, 8.0, 80.0, 78.0], [7.0, 4.0, 121.0, 60.0]]

Thanks,

Asked By: Loch

||

Answers:

Just use a list comprehension:

test = [sh.row_values(rownum) for rownum in range(sh.nrows)]
Answered By: tobias_k

Just add this line before the loop:

final = []

Then instead of print change the line to:

final.append(sh.row_values(rownum))

It should do what you ask for.

Answered By: wind85
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.