我正在实现一个图形操作脚本,我对以下错误感到困惑:
Traceback (most recent call last):
File ".....py", line 12, in <module>
print(len(graph.predecessors(i)), len(graph.successors(i)))
>>TypeError: object of type 'dict_keyiterator' has no len()<<
代码如下:
import networkx as nx
graph = nx.DiGraph()
for i in range(10):
graph.add_node(i)
for i in range(9):
graph.add_edge(i, i+1)
for i in range(10):
print(len(graph.predecessors(i)), len(graph.successors(i)))
这是什么dict_keyiterator
以及如何修复我的代码?谢谢
通过将迭代器转换为列表,问题最终得以解决:
Yakym Pirozhenko提出了一种被认为更快的替代方法,因此我检查了一下:
得到:
显然,这里的
len(list(...))
方法更快。 我在Windows10上使用的是:Python3.7经过一番搜索,我发现了一个带有similar problem和一个简单解释here的问题:
因此,在Python 3中直接使用
iter(d)
,其中d
是dict
的结果是dict_keyiterator
类型的对象。这是替换Python 2的3个迭代器之一:d.viewkeys()
、d.viewitems()
和d.viewvalues()
:相关问题 更多 >
编程相关推荐