[英]Python -Cannot remove list item
I have to remove a particular given element.我必须删除特定的给定元素。 I used
list1=[0,1,2,2,3,0,4,2]
and remove_element=2
我使用
list1=[0,1,2,2,3,0,4,2]
和remove_element=2
def fun(list1,remove_element):
if len(list1)==0:
return 0
for i in range(len(list1)):
if remove_element==list1[i]:
list1.remove(remove_element)
return list1
here is the error i get:这是我得到的错误:
Traceback (most recent call last):
File "<pyshell#205>", line 1, in <module>
print(fun(list1,remove_element))
File "<pyshell#204>", line 5, in fun
if remove_element==list1[i]:
IndexError: list index out of range
Another shorter solution would be另一个更短的解决方案是
def fun(list1,remove_element):
while remove_element in list1:
list1.remove(remove_element)
return list1
Try this尝试这个
def fun(list1,remove_element):
if len(list1)==0:
return 0
newlist = list(filter((remove_element).__ne__, list1))
print(newlist)
return newlist
Running跑步
fun(['1', '2', '3'], '1')
get [2,3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.