为了账号安全,请及时绑定邮箱和手机立即绑定

从列表python中删除所有元素

从列表python中删除所有元素

慕婉清6462132 2023-05-09 10:02:25
我已经编写了这段代码,但它并没有从列表中删除所有元素,而是只删除了 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 循环遍历列表时它认为是一个索引号并且当您删除一些索引时您会更改它,因此它会跳过一些索引


查看完整回答
反对 回复 2023-05-09
?
呼啦一阵风

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


查看完整回答
反对 回复 2023-05-09
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

只需使用names.clear()它就会清除整个列表



查看完整回答
反对 回复 2023-05-09
  • 3 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号