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'是一个名称列表,所有字符串? –