我正在尝试将临时列表(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 [[],[]]
我哪里出错了?你知道吗
这是因为您将}表示相同的内存空间。你知道吗
temp
添加到dfl
并清除了temp
。^dfl
和temp
中的{你可以这样做来避免
您可以使用
is
运算符检查两个变量是否指向同一内存空间。你知道吗dfl.append(temp)
不附加temp
的值,而是附加对temp
的引用。您需要附加temp
的副本因为你可以用温度清除()
dfl中的temp与temp是同一个对象。你知道吗
您可以尝试:
相关问题 更多 >
编程相关推荐