Akisha Akisha - 2 years ago 104
Python Question

How to write data from 1D array to an excel file from python?

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 = [

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


Answer Source

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!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download