簡體   English   中英

Python:將列表傳遞給另一個列表但列表為空

[英]Python: pass list to another list but list is blank

我在 openpyxl 中使用 python 3.7。 我正在嘗試將工作表中的數據解析為列表。 在這個函數中,最初我是直接從一個電子表格中將信息提取到一個列表中,然后使用 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', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

任何幫助,將不勝感激。

您正在清除 for 循環內的列表,此處無需重用相同的列表,因此只需在 for 循環中對其進行初始化而不是清除它

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

這是因為您在循環的每次迭代中都重復使用相同的列表。

current_data.clear()確實清除了列表,但這與之前附加的引用相同。

要解決您的問題,只需在 for 循環內移動current_data = [] (第 4 行)並刪除current_data.clear()語句。

編輯:這是一個簡短的示例,用於演示valuereference之間的區別。

my_list = []  # my_list is a variable that is pointing to a list
other_list = my_list  # other_list is a second variable that is pointing to the same list
my_list.append(1)
print(my_list)  # Prints out "[1]"
print(other_list)  # Also print out "[1]"

我們說兩個變量都引用了同一個實例(列表)。 如果我們為my_list分配一個新列表會發生什么:

my_list = []
print(my_list)  # Prints out "[]"
print(other_list)  # Still prints out "[1]"

他們現在完全引用不同的列表。

與此相關的是“按值傳遞”和“按引用傳遞”的概念,您可能會發現了解這些概念很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM