首页 > 解决方案 > 尽管我没有清除它,但我的 Python 列表正在被清除

问题描述

我正在尝试将一个临时列表 (temp) 附加到主列表 (dfl) 中,其中临时列表会在每次 for 循环迭代时更改其中的元素。

代码片段如下 -

for i in range(1,n+1):#n is the number of rows
    for j in range(2,8):
        data = driver.find_element_by_xpath("//xpath").text #Data is derived from a website element by element
        temp.append(data)
    dfl.append(temp)
    print(dfl)
    temp.clear()

现在,print(dfl)得到了我想要的输出,[[list1],[list2]]. 但是当我print(dfl)在 for 循环之外执行相同的操作时,它会像这样打印出两个空列表[[],[]]

我哪里错了?

标签: pythonlistselenium

解决方案


dfl.append(temp)不附加 的值temp,它附加对 的引用temp。您需要附加一份temp

for i in range(1,n+1):#n is the number of rows
    for j in range(2,8):
        data = driver.find_element_by_xpath("//xpath").text #Data is derived from a website element by element
        temp.append(data)
    dfl.append(temp[:])
    print(dfl)
    temp.clear()

推荐阅读