慕婉清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 循環遍歷列表時它認為是一個索引號并且當您刪除一些索引時您會更改它,因此它會跳過一些索引

呼啦一陣風
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
提交
取消