亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從列表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 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號