python - python list.clear()函数在每次迭代后交换空列表
问题描述
我正在尝试在列表中添加数据。我使用了一个临时列表,将其数据交换到另一个列表 b,然后在每次迭代中清除其数据使用 temp.clear() 时,我的最终输出为空。但使用 temp = [] 时,我得到正确的输出。
请说明为什么使用 temp.clear() 和 temp = [] 时会出现不同的输出。
a=['apple','pizza','veg','chicken','cheese','salad','chips','veg']
b=[]
temp=[]
for i in range(len(a)):
temp.append(a[i])
b.append(temp)
temp.clear()
#temp = []
print(b)
输出
#temp.clear()
[[], [], [], [], [], [], [], []]
#temp = []
[['apple'], ['pizza'], ['veg'], ['chicken'], ['cheese'], ['salad'], ['chips'], ['veg']]
解决方案
temp.clear()
从列表中删除所有项目(请参阅文档)。temp = []
不清除任何列表。相反,它会创建一个新的空列表。由于您附加temp
到b
,因此这些值在使用时会保持不变temp = []
,但在使用时会被清除temp.clear()
。
推荐阅读
- command-line-interface - 如何在 Linux 上仅安装 ksqlDB CLI 工具?
- docker - 如何升级容器中的 Docker 映像?
- makefile - 警告:不推荐使用不同枚举类型(x 和 y)之间的算术运算如何关闭?
- xml - Android登录屏幕约束布局
- jquery - 用jquery进行数字匹配游戏。第二个选择会影响上一个选择
- react-testing-library - 查询被查询元素的子元素
- java - 如何为 Null 列表或目标返回 204 而不是 200 []
- sql - 将两行合并为一个 Postgresql
- c++ - 使用 std::enable::if 和 std::is_base_of 来约束继承
- mysql - 2个表的MySQL连接查询:返回不正确