从循环列表中填充字典

Populate dictionary from list in loop

我有以下运行良好的代码,我想知道如何使用列表理解来实现相同的逻辑。

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

另外,我是否会通过使用列表理解来提高性能?

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

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

像这样,用字典理解

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 的大小,K 是大小feature_space).