Use a collections.Counter() object,然后仅保留那些计数为 1 的值:
from collections import counter
[k for k, v in Counter(lst).items() if v == 1]
这是一个 O(N) 算法;您只需要循环遍历 N 个项目的列表一次,然后第二次循环遍历较少的项目 (
如果顺序很重要并且您使用的是 Python
counts = Counter(lst)
[k for k in lst if counts[k] == 1]
Demo:
>>> from collections import Counter
>>> lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
>>> [k for k, v in Counter(lst).items() if v == 1]
['a', 'b', 'd']
>>> counts = Counter(lst)
>>> [k for k in lst if counts[k] == 1]
['a', 'b', 'd']
两种方法的顺序相同纯属巧合。对于 Python 3.6 之前的 Python 版本,其他输入可能会导致不同的顺序。
在 Python 3.6 中,字典的实现发生了变化,现在保留了输入顺序。