python - 尽管我没有清除它,但我的 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 循环之外执行相同的操作时,它会像这样打印出两个空列表[[],[]]
我哪里错了?
解决方案
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()
推荐阅读
- google-cloud-platform - 如何将自定义元数据添加到来自 Google Cloud Storage 存储桶的 404 响应?
- javascript - 按顺序同步渲染 React 组件
- vba - MatchCase:=False).row 和“运行时错误 91”
- c++ - 带有指针的嵌套foreach循环?
- r - 从R中的字符串中删除十六进制代码
- r - 离散值和 geom_ribbon 和 geom_lines + “离散”比例的问题
- typescript - IONIC 3 Recording Audio 在第二次录音后不工作
- ios - willPresentNotification 未在 FCM 通知中调用
- node.js - 引导程序“npm 运行”错误
- go - 将预先存在的数据列表导入 Terraform