0
我想通過使用用戶輸入和for循環從列表中刪除元素。如何通過python中的用戶輸入從列表中刪除元素?
這是據我得到:
patientname = input("Enter the name of the patient: ")
for x in speclistpatient_peter:
del speclistpatient_peter
我想通過使用用戶輸入和for循環從列表中刪除元素。如何通過python中的用戶輸入從列表中刪除元素?
這是據我得到:
patientname = input("Enter the name of the patient: ")
for x in speclistpatient_peter:
del speclistpatient_peter
使用列表理解;在for
循環改變列表,而循環會導致問題,因爲列表大小的變化和指數上移:
speclistpatient_peter = [x for x in speclistpatient_peter if x != patientname]
這將重新生成列表,但遺漏了匹配輸入patientname
值的元素。
只需使用remove
方法列表:
l = ["ab", "bc", "ef"]
l.remove("bc")
從l
刪除elment "bc"
。
推測'speclistpatient_peter'是一個名稱列表,所有字符串? –