-1

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,

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Loch
  • 3
  • 1

2 Answers2

0

Just use a list comprehension:

test = [sh.row_values(rownum) for rownum in range(sh.nrows)]
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • I know the OP doesn't ask for this, per se, but I like your answer and I think you could add this bit to it: this can be expanded slightly so as to [append the names of each column to the row values](http://stackoverflow.com/a/23568655/5209610): `for row_index in xrange(1, sheet.nrows): test = [ {keys[col_index]: sheet.cell(row_index, col_index).value for col_index in range(sh.ncols)} for row_index in range(sh.nrows) ]` it might be helpful for someone viewing this question. – Vladislav Martin Jun 15 '16 at 13:54
0

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.

wind85
  • 487
  • 2
  • 5
  • 11