【问题标题】:Populate dictionary from list in loop从循环列表中填充字典
【发布时间】:2016-11-25 08:51:38
【问题描述】:

我有以下代码可以正常工作,我想知道如何使用列表理解来实现相同的逻辑。

def get_features(document, feature_space):
    features = {}
    for w in feature_space:
        features[w] = (w in document)
    return features

我还会通过使用列表推导来提高性能吗?

问题是feature_spacedocument 都比较大,会运行很多次迭代。

编辑:很抱歉一开始没有说清楚,feature_spacedocument 都是列表。

  • document 是一个单词列表(一个单词可能存在不止一次!)
  • feature_space 是标签(特征)列表

【问题讨论】:

  • 什么是document?如果不是集合或字典,那就做一个。
  • @MartijnPieters 看到我的编辑。谢谢我做到了。

标签: python python-3.x dictionary-comprehension


【解决方案1】:

像这样,带有dict理解

def get_features(document, feature_space):
    return {w: (w in document) for w in feature_space}

features[key] = value 表达式在开头成为key: value 部分,其余的for 循环和任何if 语句按照嵌套顺序排列。

是的,这将提高性能,因为您现在已删除所有 features 本地名称查找和 dict.__setitem__ 调用。

请注意,您需要确保document 是一种具有快速成员资格测试的数据结构。如果是列表,首先将其转换为set(),例如,以确保成员资格测试花费 O(1)(常数)时间,而不是列表的 O(n) 线性时间:

def get_features(document, feature_space):
    document = set(document)
    return {w: (w in document) for w in feature_space}

使用set,现在这是一个 O(K) 循环而不是 O(KN) 循环(其中 N 是 document 的大小,Kfeature_space) 的大小。

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多