我的Python列表正在清除,尽管我没有清除我的

2024-10-06 12:31:06 发布

您现在位置: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]]。 但是当我在for循环外执行相同的print(dfl)时,它会打印出两个空列表,如so [[],[]]

我哪里出错了?你知道吗


Tags: 代码in元素列表fordatabyis
3条回答

这是因为您将temp添加到dfl并清除了temp。^dfltemp中的{}表示相同的内存空间。你知道吗

你可以这样做来避免

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)

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

因为你可以用温度清除()

dfl中的temp与temp是同一个对象。你知道吗

您可以尝试:

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

相关问题 更多 >