我有以下设置:迭代它时修改集合是否有任何危险?
co_occurrences = defaultdict(lambda: defaultdict(int))
# Populate the dictionary...
for word, occurrence_vector in co_occurrences:
if word == "__length": continue
for file_name, occurrence_count in occurrence_vector:
co_occurrences[word][file_name] = occurrence_count/co_occurrences["__length"][file_name]
这是行:
co_occurrences[word][file_name] = occurrence_count/co_occurrences["__length"][file_name]
危险吗?由于危险,我的意思是我想遍历每个键一次,只有一次,所以修改此行为的任何代码都是危险的。我觉得可能是因为我正在修改我正在迭代的数据结构。
你可以通过使用co_occurrences.keys()中的for word来解决这个问题:occurrence_vector = co_occurrences [word]'它会生成密钥列表的一个副本并对其进行迭代。 – Perkins
在你的字典里还有一个魔术入口'“__length”'真的很奇怪。只需制作一个将文件名映射到其长度的'file_length'字典。 – U2EF1
相关:http://stackoverflow.com/a/2315529/846892 –