(Python)我的清单被清除了,尽管我没有清除

时间:2019-12-31 06:50:23

标签: python list selenium

我正在尝试将一个临时列表(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]]。 但是,当我在for循环外执行相同的print(dfl)时,它会像这样[[],[]]

打印出两个空列表

有人能找到我要去的地方吗?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

因为您使用temp.clear()清除了它

dfl中的温度与温度是同一对象。

您可以尝试:

import copy
...
dfl.append(copy.deepcopy(temp))

答案 2 :(得分:0)

这是因为您将temp添加到dfl并清除了temptempdfl中的temp引用相同的内存空间。

您可以这样做以避免这种情况

dfl.append(temp[:]) # [:] is a way of copying using slicing

您可以使用is运算符检查两个变量是否指向相同的内存空间。

>>> a=[1,2,3]
>>> b=a
>>> a is b
True
>>> id(a),id(b)
(1363188582536, 1363188582536)