問題描述
給定一個字符串列表,我想刪除重復的單詞和原始單詞.
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.
這篇關于從列表中刪除重復項和原始項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!