如何从1D数组写入数据到python的excel文件?

时间:2016-06-02 18:37:36

标签: python arrays excel xlsxwriter

我是python的新手,我必须将此代码更改为具有一维数组而不是二维数组。此代码完全可以将数据写入excel文件。请帮我改成一维数组。

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()

1 个答案:

答案 0 :(得分:1)

这个问题基本上归结为元组解包,原始代码中的for循环基本上是为expenses中的每个项目执行此操作:

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

如果expenses的每个元素只包含一个元素,您可以在变量后面用一个尾随逗号解包单个元素(就像使用单个元素元组一样)

item, = [1000]  #unpacks 1000 to item

所以在for循环中它只是:

for item, in (expenses):
     #  ^ the trailing comma here!