# 如何删除列表中重复数字的所有实例？

2023-08-22 16:07:18

## 5 回答

TA贡献1784条经验 获得超2个赞

>>> from collections import Counter

>>> l = [2, 3, 6, 6, 8, 9, 12, 12, 14]

>>> res = [el for el, cnt in Counter(l).items() if cnt==1]

>>> res

[2, 3, 8, 9, 14]

TA贡献1831条经验 获得超10个赞

Inputlist = [2, 3, 6, 6, 8, 9, 12, 12, 14]

seen = set()

ans = set()

for el in Inputlist:

if el not in seen:

else:

print(list(ans))

from timeit import timeit

first = """

def get_from_two_sets():

seen = set()

ans = set()

for el in (2, 3, 6, 6, 8, 9, 12, 12, 14):

if el not in seen:

else:

second = """

def get_from_counter():

return [el for el, cnt in Counter((2, 3, 6, 6, 8, 9, 12, 12, 14)).items() if cnt == 1]

"""

print(timeit(stmt=first, number=10000000))

print(timeit(stmt=second, number=10000000, setup="from collections import Counter"))

0.3130729760000577

0.46127468299982866

@abc 解决方案很干净并且Pythonic，那就去做吧。

TA贡献1851条经验 获得超3个赞

Inputlist = [2, 3, 6, 6, 8, 9, 12, 12, 14]

Outputlist = [item for item in Inputlist if Inputlist.count(item) == 1]

TA贡献1876条经验 获得超5个赞

l = [2, 3, 6, 6, 8, 9, 12, 12, 14]

inset = set(l)

for i in inset:   # <-- usually the element to remove is in the front,

l.remove(i)   # <-- but in a worst case, this is slower than O(n)

result = list(inset - set(l))

# %timeit this solution

1.18 µs ± 1.97 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# %timeit solution with seen-set

1.23 µs ± 1.49 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# %timeit solution with Counter class

2.76 µs ± 4.85 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

TA贡献2012条经验 获得超12个赞

from itertools import groupby

inputlist = [2, 3, 6, 6, 8, 9, 12, 12, 14]

outputlist = [x for _, (x, *extra) in groupby(inputlist) if not extra]

outputlist = [x for x, grp in groupby(inputlist) if ilen(grp) == 1]

def more_than_one(it):

next(it)  # Assumes at least once, which is already the case with groupby groups

try:

next(it)

except StopIteration:

return True

return False

outputlist = [x for x, grp in groupby(inputlist) if not more_than_one(grp)]

• 5 回答
• 0 关注
• 1592 浏览

0/150