0

I'm new to python and I have to change this code to have a 1D array not a 2D array.This code is perfectly working to write data to an excel file. Please help me to change this in to a 1D array.

eg: only to enter as 1D array as below
  expenses = [
        [1000],
        [100],
        [300],
        [50],
    ]

import xlsxwriternter 

workbook = xlsxwriter.Workbook('20.xlsx')
worksheet = workbook.add_worksheet()

expenses = [
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
]


row = 0
col = 0


for item,cost in (expenses):
    worksheet.write(row, col,     item)

    row += 1



workbook.close()
6
  • I do not understand your question, you are incrementing row so it is placing the items in rows, if you instead incremented col it would write to separate columns... Commented Jun 2, 2016 at 18:42
  • No actually what I need is to pass data from a 1D array and print to an excel sheet. This is a sample example I found from a reference tutorial.xlsxwriter.readthedocs.io/tutorial01.html Commented Jun 2, 2016 at 18:44
  • so change it so that it works with the first expenses list? that would be easy, just change for item,cost in (expenses): to for item, in (expenses): so that you are unpacking only one item and not two. Commented Jun 2, 2016 at 18:49
  • I was trying to do that as you told but it throws this error -->TypeError: Unsupported type <type 'list'> in write() Commented Jun 2, 2016 at 18:51
  • 1
    you missed the trailing comma: for item, in... this means you are unpacking a single element from the list, either that or you do for item in expenses:thing_to_write = item[0] Commented Jun 2, 2016 at 18:53

1 Answer 1

1

This question basically comes down to tuple unpacking, the for loop in the original code was basically doing this for each item in expenses:

item, cost = ['Rent', 1000] #unpacks 'Rent' to item and 1000 to cost

if each element of expenses consisted of only a single element you would unpack a single element with a trailing comma after the variable (like how you do with a single element tuple)

item, = [1000]  #unpacks 1000 to item

so in the for loop it would just be:

for item, in (expenses):
     #  ^ the trailing comma here!
Sign up to request clarification or add additional context in comments.

Comments

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.