代码如下:
A = [1,5,3,89,7,4,82,6,66,89,1,3,8,1000,66,8,9,4,6,8,5,5,5,5,5,5,5,5,1000,1000,5]
for i in A:
n = A.count(i)
print(i,n)
while n > 1:
A.remove(i)
n -= 1
print(A)
结果中忽略了1000
代码如下:
A = [1,5,3,89,7,4,82,6,66,89,1,3,8,1000,66,8,9,4,6,8,5,5,5,5,5,5,5,5,1000,1000,5]
for i in A:
n = A.count(i)
print(i,n)
while n > 1:
A.remove(i)
n -= 1
print(A)
结果中忽略了1000
注意:python在遍历过程中删除元素是大忌,即使必须这么做也得三思而后行
看你的代码需要实现的是去重功能,下面提供两种简单的方式:
1.使用另一个列表保存结果:
A = [1,5,3,89,7,4,82,6,66,89,1,3,8,1000,66,8,9,4,6,8,5,5,5,5,5,5,5,5,1000,1000,5]
B = []
for i in A:
if i not in B:
B.append(i)
print (B)
2.使用set, 集合天生自带去重功能
A = [1,5,3,89,7,4,82,6,66,89,1,3,8,1000,66,8,9,4,6,8,5,5,5,5,5,5,5,5,1000,1000,5]
B = []
B= list(set(A))
print (B)
还有其他库行数可以调用实现,比如itertools模块的grouby等,有兴趣可以百度一下
如果非要在原列表中进行操作的话可以倒序遍历将你的for i in A换成for i in A[::-1],但这种方式也不建议采取,使用set最简洁而高效