繁体   English   中英

运行时错误:字典在迭代期间改变了大小

[英]runtime error: dictionary changed size during iteration

我有一个社交网络图“G”。

我正在尝试检查我的图表的键是否也在特征数据集中。 我运行了这个命令:

for node in G.nodes():
    if node in caste1.keys():
        pass
    else:
        G = G.remove_node(node)

它显示一个错误 RuntimeError: dictionary changed size during iteration

RuntimeError是不言自明的。 您正在更改在迭代中迭代的 object 的大小。 它弄乱了循环。

您可以做的是首先遍历节点以获取要删除的节点,并将其存储在单独的变量中。 然后您可以使用此变量进行迭代以删除节点:

# Identify nodes for removal
nodes2remove = [node for node in G.nodes() if node not in caste1.keys()]

# Remove target-nodes
for node in nodes2remove:
    G = G.remove_node(node)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM