【问题标题】:How to remove duplicate phrases from list of dicts? [duplicate]如何从字典列表中删除重复的短语? [复制]
【发布时间】:2018-10-30 21:19:16
【问题描述】:

我有以下方法,它接受一个字典列表并返回一个新列表,其中仅包含具有唯一 phrases 的字典

@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

有什么方法可以加快速度吗?

【问题讨论】:

  • 您能否展示一下您是如何运行它并解释为什么您认为它很慢?

标签: python python-3.x algorithm


【解决方案1】:

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

>>> 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

【讨论】:

    猜你喜欢
    • 2022-11-27
    • 2019-07-01
    • 2011-10-28
    • 1970-01-01
    • 2013-09-01
    • 2023-01-08
    • 1970-01-01
    • 2012-02-16
    相关资源
    最近更新 更多