计算我删除列表中元素的次数 python

count how many times I remove an element in a list python

我需要记录从列表中删除某个元素的次数。我有类似 list remove(an element) 的东西。

我试过了:

c=0
list remove(an element)
c+=1

您必须在整个列表中引入一个 for 循环,然后使用计数器 c。你必须在循环外初始化 c 并在循环外打印 c ,如:

c=0
for i in range(0,len(list)):
    if element in list:
        list.remove(element)
        c+=1
print(c)

删除前后列表长度的差异将告诉您删除了多少。

pre_len = len(list)
list = [x for x in list if x != needle]
num_removed = pre_len - len(list)