Python-按名称从列表中删除元素的函数
Python- Function which deletes an element from a list by name
您好,我想弄清楚如何使用列表中该元素的特定名称从列表中删除该元素。所以会有一个输入,用户将被询问 'who do you want to delete from the list: ',他们将输入名字。我似乎不知道该怎么做。我将个人的所有详细信息保存在一个名为 "student" 的变量中,其中包含他们的姓名、课程等。
def removestudent():
for studentName in student:
del(student)
input("insert the user you wish to remove: "
我想你想要remove
>>> l = ['a','b','c','e']
>>> l.remove('a')
>>> l
['b', 'c', 'e']
你可以做到:
l = ['a, 'b','c']
a = [x for x in l if x != 'a']
a
>>>['b','c']
您需要将参数传递给函数 elem
是您要从列表中删除的元素 l
是列表:
>>> def removestudent(elem,l):
... l.remove(elem)
... return l
...
>>> l=[1,2,3,4]
>>> removestudent(input("insert the user you wish to remove: "),l)
insert the user you wish to remove: 3
[1, 2, 4]
但是这里有一个问题,如果元素不在您的列表中 python 将引发一个 ValueError
:要摆脱它,您需要使用一个 try-except
语句:
>>> def removestudent(elem,l):
... try :
... l.remove(elem)
... return l
... except ValueError :
... print 'The element is not in list please enter a valid element !!'
...
>>> removestudent(input("insert the user you wish to remove: "),l)
insert the user you wish to remove: 7
The element is not in list please enter a valid element !!
您好,我想弄清楚如何使用列表中该元素的特定名称从列表中删除该元素。所以会有一个输入,用户将被询问 'who do you want to delete from the list: ',他们将输入名字。我似乎不知道该怎么做。我将个人的所有详细信息保存在一个名为 "student" 的变量中,其中包含他们的姓名、课程等。
def removestudent():
for studentName in student:
del(student)
input("insert the user you wish to remove: "
我想你想要remove
>>> l = ['a','b','c','e']
>>> l.remove('a')
>>> l
['b', 'c', 'e']
你可以做到:
l = ['a, 'b','c']
a = [x for x in l if x != 'a']
a
>>>['b','c']
您需要将参数传递给函数 elem
是您要从列表中删除的元素 l
是列表:
>>> def removestudent(elem,l):
... l.remove(elem)
... return l
...
>>> l=[1,2,3,4]
>>> removestudent(input("insert the user you wish to remove: "),l)
insert the user you wish to remove: 3
[1, 2, 4]
但是这里有一个问题,如果元素不在您的列表中 python 将引发一个 ValueError
:要摆脱它,您需要使用一个 try-except
语句:
>>> def removestudent(elem,l):
... try :
... l.remove(elem)
... return l
... except ValueError :
... print 'The element is not in list please enter a valid element !!'
...
>>> removestudent(input("insert the user you wish to remove: "),l)
insert the user you wish to remove: 7
The element is not in list please enter a valid element !!