【发布时间】:2020-05-28 14:23:01
【问题描述】:
我有像words = ['a', 'spam', 'an', 'eggs', 'the', 'foo', 'and', 'bar'] 这样的单词列表。
我想排除一些在另一个列表中定义的词(停用词)或设置stop_words = ['a', 'an', 'the', 'and']。
做到这一点并保持原始列表顺序的最快方法是什么?我尝试使用set() 甚至SortedSet()。但是还是没用,单词还是和原来的顺序不一样。
r1 = set(words) - set(stop_words)
r2 = SortedSet(words) - SortedSet(stop_words)
尝试一个一个地迭代,但不确定它在大列表上是否足够快。
r3 = [w for w in words if w not in stop_words]
【问题讨论】:
-
最快的方法可能是建立一个Trie(前缀树)并用它来检查你的话。为了保持顺序,您必须调整 Trie 以考虑我想象的单词/字母的顺序。
-
按顺序遍历您的输入列表并丢弃您在停用词 Trie 中找到的单词。那么您应该能够保留订单。
标签: python python-3.x list algorithm set