在python中,我必须在列表数据类型中使用remove()删除所有相同的occurance元素
我编写了一个代码,用于使用#remove方法从列表中删除相同的引用元素remove在python中,我必须在列表数据类型中使用remove()删除所有相同的occurance元素,python,list,Python,List,我编写了一个代码,用于使用#remove方法从列表中删除相同的引用元素remove l=[1,1,1,2,2,2,2,3,3] x=int(input("enter the element given in the list:"))#when input is 2 for i in l: if i==x: l.remove(i) print(l) 但是o/p:即将到来[1,1,1,2,2,3,3] 但是所有2个都应该删除,但不删除在迭代列表时不要删除元素,结果可能是
l=[1,1,1,2,2,2,2,3,3]
x=int(input("enter the element given in the list:"))#when input is 2
for i in l:
if i==x:
l.remove(i)
print(l)
但是o/p:即将到来[1,1,1,2,2,3,3]
但是所有2个都应该删除,但不删除在迭代列表时不要删除元素,结果可能是意外的 相反,请尝试使用列表理解分配新列表:
l = [x for x in l if x != 2]
或者更好地使用filterfalse
等工具