python - 如何加快大字典的迭代速度

标签 python loops dictionary

我有一个字典,其中分别包含键值对 sentence_IDcluster_ID

格式如下:{sentence_ID : cluster_ID}

示例:

my_id_dict:
    {0: 71, 
    1: 63, 
    2: 66, 
    3: 92, 
    4: 49, 
    5: 85
      .
      .}

总共,我有200,000多个sentence_IDs100个cluster_IDs

我正在尝试循环 my_id_dict 为每个集群生成一个sentence_ids 列表

我想要的示例输出:

Cluster 0
[63, 71, 116, 168, 187, 231, 242, 290, 330, 343]

Cluster 1
[53, 107, 281, 292, 294, 313, 353, 392, 405, 479]

这是我使用的代码:

逻辑是,对于每个簇,创建一个句子列表,然后对于所有200,000多个dict值中的cluster_id,如果dict值==当前簇索引,则将句子ID写入句子列表。

继续100次。

    cluster_dict = defaultdict(list)
    num_clusters = 100

    for cluster in xrange(0,num_clusters):
        print "\nCluster %d" % cluster

        sentences = []
        for i in xrange(0,len(my_id_dict.values())):
            if( my_id_dict.values()[i] == cluster ):
                sentences.append(my_id_dict.keys()[i])

        cluster_dict[cluster] = sentences
        print sentences[:10]

这可以工作,但是速度非常慢。有没有更快的方法可以做到这一点?

最佳答案

您将检查每个集群的每个句子。只需检查每个句子一次,将其分配到一个簇:

cluster_dict = defaultdict(list)
for sentence, cluster in my_id_dict.items():
    cluster_dict[cluster].append(sentence)

关于python - 如何加快大字典的迭代速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349337/

相关文章:

python - 我可以从内存中的字符串导入 python 模块吗?

python - 未实现错误: Django doesn't provide a DB representation

ruby - 如何在 Ruby 中重新启动或重用 case 语句?

python - 使用 Python 从 linux 命令行读取

python - numpy.disutils.system_info.NotFoundError : no lapack/blas resources found

c - 通过 scanf 读取一行但读取了两次

java - Java移位运算符0十六进制数

python - 类 python 的实例的 getattr 查找失败

java - 流式生成带有整数键和值集的映射

c# - 公共(public)静态 Dictionary<String,GameObject> 中的游戏对象在 Unity 中的场景更改时被销毁