从列表中删除重复项和原始项
问题描述
给定一个字符串列表,我想删除重复的单词和原始单词.
Given a list of strings I want to remove the duplicates and original word.
例如:
lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
输出应删除重复项,所以像这样 ['a', 'b', 'd']
The output should have the duplicates removed,
so something like this ['a', 'b', 'd']
我不需要保留订单.
解决方案
使用 collections.Counter()
object,然后只保留那些计数为 1 的值:
Use a collections.Counter()
object, then keep only those values with a count of 1:
from collections import counter
[k for k, v in Counter(lst).items() if v == 1]
这是一个 O(N) 算法;您只需要遍历 N 个项目的列表一次,然后再对更少的项目 (< N) 进行第二次循环,以提取那些只出现一次的值.
This is a O(N) algorithm; you just need to loop through the list of N items once, then a second loop over fewer items (< N) to extract those values that appear just once.
如果顺序很重要并且您正在使用 Python <3.6、分离步骤:
If order is important and you are using Python < 3.6, separate the steps:
counts = Counter(lst)
[k for k in lst if counts[k] == 1]
演示:
>>> 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 版本,其他输入可能会导致不同的顺序.
That the order is the same for both approaches is a coincidence; for Python versions before Python 3.6, other inputs may result in a different order.
在 Python 3.6 中,字典的实现发生了变化,现在保留了输入顺序.
In Python 3.6 the implementation for dictionaries changed and input order is now retained.
相关文章