1
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.

2 Answers 2

1

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

Comments

0

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)

7 Comments

That does it ! Thanks
How can I use those values from those arrays individually for something ?
@MasterMind You can do print(test[0][2]) to print 3rd column from the first row for example.
With the original problem, I had I am not getting those words in the array. What am I missing?
I'm not really getting. Which "those words" in which array?
|

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.