Python 如何从dicts列表中删除重复的短语?

Python 如何从dicts列表中删除重复的短语?,python,python-3.x,algorithm,Python,Python 3.x,Algorithm,我有以下方法,它获取一个dict列表并返回一个新列表,其中只包含具有唯一短语的dict @staticmethod def remove_duplicate_phrases(words: List[Dict[str, Any]]): unique_phrases, unique_words = set(), [] for word in words: if word['phrase'] not in unique_phrases: uniq

我有以下方法,它获取一个dict列表并返回一个新列表,其中只包含具有唯一
短语的dict

@staticmethod
def remove_duplicate_phrases(words: List[Dict[str, Any]]):
    unique_phrases, unique_words = set(), []
    for word in words:
        if word['phrase'] not in unique_phrases:
            unique_phrases.add(word['phrase'])
            unique_words.append(word)
    return unique_words

有什么方法可以让它更快吗?

这是我通常选择的最干净的方式:

>>> list_ = [
    {"phrase": 1},
    {"phrase": 1},
    {"phrase": 2},
    {"phrase": None}
]

>>> list(set([dict_['phrase'] for dict_ in words]))
[1, 2, None]
上面的例子说明了如何清理字典列表,尽管性能不会有实质性的提高;解决方法也取决于你传递的单词数量

set()
在需要无序的唯一元素集合的情况下非常有用

将此答案中的解决方案与您的解决方案在大约2000个元素上运行3次,结果表明此答案中的解决方案略快

# solution in answer
0.001382553018629551

# your solution
0.002490615996066481

你能展示一下你是如何运行它的,并解释一下你为什么认为它慢吗?