Helenr
删除重复使用set(a)..要打印副本,如下所示:a = [1,2,3,2,1,5,6,5,5,5]import collectionsprint [item for item, count in collections.Counter(a).items() if count > 1]## [1, 2, 5]请注意Counter不是特别有效(计时)而且可能会在这里过度杀戮。set会表现得更好。此代码按源顺序计算唯一元素的列表:seen = set()uniq = []for x in a:
if x not in seen:
uniq.append(x)
seen.add(x)或者,更简单地说:seen = set()uniq = [x for x in a if x not in seen and not seen.add(x)]我不推荐后一种风格,因为不明显的是not seen.add(x)正在做(套装)add()方法总是返回None,因此需要not).若要计算没有库的重复元素列表,请执行以下操作:seen = {}dupes = []for x in a:
if x not in seen:
seen[x] = 1
else:
if seen[x] == 1:
dupes.append(x)
seen[x] += 1如果列表元素不可接受,则不能使用SET/DECTS,而必须使用二次时间解决方案(将每一项与每一项进行比较)。例如:a = [[1], [2], [3], [1], [5], [3]]no_dupes = [x for n, x in enumerate(a) if x not in a[:n]]print no_dupes # [[1], [2], [3], [5]]
dupes = [x for n, x in enumerate(a) if x in a[:n]]print dupes # [[1], [3]]
MM们
>>> l = [1,2,3,4,4,5,5,6,1]>>> set([x for x in l if l.count(x) > 1])set([1, 4, 5])