如下代码,遍历列表,删除列表中的偶数时,结果与预期不符. a = [11, 20, 4, 5, 16, 28] for i in a: if i % 2 == 0: a.remove(i) print a 得到的结果为: >>> [11, 4, 5, 28] 其中偶数4和28都没有删掉,原因在于for循环在遍历列表时,是按照元素的索引依次访问元素的,当删除其中一个元素后,后面的元素会依次前移,即就是删除索引1处的元素20后,将访问索引为2的元素,但由于删除元素20之后,后面的元素会依次前…
通常涉及到去重操作最好使用set,但是考虑到某些时候可能遇到不允许使用set的情况,那就自己实现一下: l = [2, 4, 5, 6, 1, 3, 4, 5] def f(l, b=0, c=1): a = len(l) if a > 1: l.sort() if l[b] == l[c]: l.pop(b) a = len(l) # 删除一个元素之后,列表的长度变了,同时,下标b和c对应的值也变了,所以重新对a赋值,而b和c不变 else: b, c = c, c+1 if a > c:…
方法1:使用set函数 s=set(list),然后再list(s) 方法2:append def delList(L): L1 = [] for i in L: if i not in L1: L1.append(i) return L1 print(delList([1,2,2,3,3,4,5])) print(delList([1,8,8,3,9,3,3,3,3,3,6,3])) 方法3:count,remove def delList(L): for i in L: if…