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,
Answers:
Just use a list comprehension:
test = [sh.row_values(rownum) for rownum in range(sh.nrows)]
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.
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,
Just use a list comprehension:
test = [sh.row_values(rownum) for rownum in range(sh.nrows)]
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.