Bob
Bob

Reputation: 23

How do I create an array of multiple values extracted from the rows and columns of excel

import xlrd

fw = 'C://Users/MM/Desktop/'

test=[]

wb1 = xlrd.open_workbook(fw + 'assignment.xls')
sh1 = wb1.sheet_by_index(0)

for a in range(2,sh1.nrows):    
    for b in range(0,sh1.ncols):
        test.append(sh1.cell(a,b).value)
print(test)

I have this code, but it is not doing what I want it to do. The output I am getting is

[0,200,clothes,1,300,shoes,2,900,food]

But, instead I want to have:

[0,200,clothes],[1,300,shoes],[2,900,food]

I can't think of anyway to get that. What I want is the code to read each row's data from every column and put it in the form I have above. "0" is column 0, "200" is in column 1, "clothes" is in column 2. I am sure this is know from the code I have.

Upvotes: 1

Views: 354

Answers (2)

khelwood
khelwood

Reputation: 59096

You can use nested list comprehensions for things like this.

test = [[sh1.cell(a,b).value for b in range(0, sh1.ncols)] for a in range(2, sh1.nrows)]

Upvotes: 1

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

You have to create a new list for each row on every row iteration:

test = []

for a in range(2, sh1.nrows):
    row = []
    for b in range(0, sh1.ncols):
        row.append(sh1.cell(a, b).value)
    test.append(row)

print(test)

Upvotes: 0

Related Questions