我有以下设置:
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]
危险吗?危险,我的意思是我想迭代每个键一次,只有一次,所以修改这种行为的任何代码都是危险的。我觉得可能是因为我正在修改我正在迭代的数据结构。
答案 0 :(得分:3)
如上所述,通常很好,如果字典的大小发生变化,唯一的问题就出现了。如果发生这种情况,它将抛出一个Exception
并停止执行,所以如果它在没有RuntimeError
的情况下执行,那么无论你做什么都没关系。
答案 1 :(得分:2)
如果要更改正在迭代的数据的结构,那将是危险的。添加/删除键,否则编辑现有键完全没问题。