[英]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.