我有一個大名單(25000項,14000個字)這樣的(大)列表中刪除所有字符串:提高性能:在只出現一次
之前(請看看下面的右邊的列表) :
texts = ['Lorem hello ipsum', 'Lorem ipsum generator machine', ... 'hello Lorem ipsum']
我想刪除整個目錄只出現一次的所有單詞。
後:
texts = ['Lorem generator ipsum', 'Lorem ipsum generator machine', ..., 'Machine Lorem ipsum']
我現在已經這樣做,但它確實慢(約2小時)。
all_tokens = sum(texts, [])
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1)
texts = [[word for word in text if word not in tokens_once] for text in texts]
如何提高性能?
編輯:
@DSM是正確的,我的輸入列表看起來像這樣。是我的錯,對不起:
texts = [['Lorem', 'hello', 'ipsum'], ['Lorem', 'ipsum', 'generator', 'machine'], ... ['hello, 'Lorem', 'ipsum']]
可能重複的[只在一個非常大的列表中出現過濾項目](http://stackoverflow.com/questions/10468974/filter-items-that-only-occurs-once-in-a-very-大名單) – Daenyth
謝謝@Daenyth,但建議的副本不是重複的。 OP正在詢問如何刪除所有單詞。 – Ben
你說「單詞」,但你從來沒有做過任何分裂,從多字詞字符串中獲取單詞(看起來像什麼樣)。這是一個疏忽嗎?編輯:如果'texts'是列表的列表,'sum(texts,[])'只能「工作」(它會很慢),但是你的'texts'是一個字符串列表。 – DSM