简体   繁体   中英

How to remove an element from a list by user input in python?

I want to remove an element from a list by using a user input and a for loop.

This is as far I got:

patientname = input("Enter the name of the patient: ") 
for x in speclistpatient_peter:                
    del speclistpatient_peter

Just use the remove method for lists:

 l = ["ab", "bc", "ef"]
 l.remove("bc")

removes the elment "bc" from l .

Use a list comprehension; altering a list in a for loop while looping can lead to problems as the list size changes and indices shift up:

speclistpatient_peter = [x for x in speclistpatient_peter if x != patientname]

This rebuilds the list but leaves out the elements that match the entered patientname value.

This line is incorrect:

patientname = input("Enter the name of the patient: ") 

Putting anything in the input() function rather than the specific thing you want to delete or find from the list will cause an error. In your case you added ("Enter the name of the patient: ") , so after the execution it will search for "Enter the name of the patient: " in the list but its not there.

Here is how you can delete a specific item from the list. You don't have use loop, instead you can delete it by using the remove() function:

print("Enter the item you want to delete")
patientname = input() # Dont Put anything between the first bracket while using input()
speclistpatient_peter.remove(patientname)
print(speclistpatient_peter)
print("Enter the item you want to delete") patientname = input() # Dont Put anything between the first bracket while using input() speclistpatient_peter.remove(patientname) print(speclistpatient_peter)

To remove a certain element: speclstpatient_peter.remove('name')


If the array contains 2x the same element and you only want the firstm this will not work. Most dynamic is just a counter instead of a pointer:

x=0
while x<len(speclistpatient_peter):
    if speclistpatient_peter[x].find(something):   # or any if statement  
         del(speclistpatien_peter[x])
    else:
         x=x+1

or make a function to keep it readable:

def erase(text, filter):
    return [n for n in text if n.find(filter)<0] 

a = ['bart', 'jan']
print erase(a, 'rt')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM