我已经编写了这段代码,但它并没有从列表中删除所有元素,而是只删除了 3 个项目。请检查我做错了什么names = ["John","Marry","Scala","Micheal","Don"]if names: for name in names: print(name) print(f"Removing {name} from the list") names.remove(name)print("The list is empty")
3 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
要实际就地清除列表,您可以使用以下任何一种方式:
alist.clear() # Python 3.3+, most obvious
del alist[:]
alist[:] = []
alist *= 0 # fastest
并且您的代码的问题是名称必须是names[:] 因为当 for 循环遍历列表时它认为是一个索引号并且当您删除一些索引时您会更改它,因此它会跳过一些索引
呼啦一阵风
TA贡献1802条经验 获得超6个赞
names = ["John","Marry","Scala","Micheal","Don"]
if names:
for name in names[:]:
print(name)
print(f"Removing {name} from the list")
names.remove(name)
print("The list is empty")
只需在 for 循环中按名称 [:] 分配全名列表
John
Removing John from the list
Marry
Removing Marry from the list
Scala
Removing Scala from the list
Micheal
Removing Micheal from the list
Don
Removing Don from the list
The list is empty
添加回答
举报
0/150
提交
取消