首页 > 解决方案 > Python:将列表传递给另一个列表但列表为空

问题描述

我正在将 python 3.7 与 openpyxl 一起使用。我正在尝试将数据从工作表解析为列表。在这个函数中最初我是直接从一个电子表格中提取信息到一个列表中,然后使用 openpyxl 粘贴到另一个工作表中,但是我无法使用 excel 过滤器等,所以现在我正在尝试编辑列表中的信息。问题是,当我尝试将信息解析到该列表时,它在 current_data 中显示得很好,但是当我附加列表时,我得到了不同的信息,几乎就像它正在覆盖列表一样。请参阅下面的函数和输出。先感谢您。

def cut_sheet_up(wsn, nws, output_log):
    x=0
    ws = wb[wsn]
    current_data = []
    for rowOfCellObjects in ws.iter_rows(min_row=0, min_col=0):
        current_data.clear()
        for cellObj in rowOfCellObjects:
            if cellObj.value is None:
                current_data.append('')
                # print causes ' value in front of string
            elif isinstance(cellObj.value, datetime) or isinstance(cellObj.value, time):
                current_data.append(cellObj.value)
            else:
                current_data.append(str(cellObj.value))
        nws.append(current_data)
        if wb[wsn] == wb['output_log']:
            x+=1
            print(current_data)
            output_log.append(current_data)
        else:
            pass

前 150 行左右作为 current_data 下的实际信息打印,其余行打印如下。

['foo', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

在工作表中,我将信息传递给我使用当前函数接收正确的数据。但是,当我在函数之后执行 print(output_log) 时,我得到所有 1500 行

['foo', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

任何帮助,将不胜感激。

标签: pythonexcellistfunctionopenpyxl

解决方案


You're clearing the list inside the for loop, theres no need to reuse the same list here, so just initialize it within the for loop instead of clearing it

for rowOfCellObjects in ws.iter_rows(min_row=0, min_col=0):
    current_data = []

推荐阅读