我正在实现一个图形操作脚本,但我对以下错误感到困惑:
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
以及如何修复我的代码?谢谢!
最佳答案
该问题最终可以通过将迭代器转换为列表来解决:
print(len(list(graph.predecessors(i))), len(list(graph.successors(i))))
Yakym Pirozhenko 提出了一种被认为更快的替代方法,所以我检查了:def f1():
for i in range(10):
len(list(graph.predecessors(i)))
def f2():
for i in range(10):
sum(1 for _ in graph.predecessors(i))
print(timeit.timeit(f1, number=100000))
print(timeit.timeit(f2, number=100000))
并得到:0.529827729
0.652576311
显然,len(list(...))
方法在这里更快。我使用的是:Windows 10 上的 Python 3.7。
经过一番搜索,我发现了一个 similar problem 的问题。和一个简单的解释 here :
In 2.x
iter(some_dict)
returns a dictionary-keyiterator (weird hyphen). In 3.x it's adict_keyiterator
(normal underscore).
所以好像直接用
iter(d)
哪里d
是 dict
导致 dict_keyiterator
类型的对象在 Python 3 中。这是替换 Python 2 的 3 个迭代器之一:d.viewkeys()
, d.viewitems()
, 和 d.viewvalues()
:The corresponding iterators returned by
iter()
in 3.x aredict_keyiterator
,dict_itemiterator
, anddict_valueiterator
.
关于python - 在计算 networkx 中的传出和传入边缘时,len 抛出 'dict_keyiterator' 没有 len(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53584341/