python - 在计算 networkx 中的传出和传入边缘时,len 抛出 'dict_keyiterator' 没有 len()

标签 python python-3.x networkx

我正在实现一个图形操作脚本,但我对以下错误感到困惑:

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 a dict_keyiterator (normal underscore).


所以好像直接用iter(d)哪里ddict导致 dict_keyiterator 类型的对象在 Python 3 中。这是替换 Python 2 的 3 个迭代器之一:d.viewkeys() , d.viewitems() , 和 d.viewvalues() :

The corresponding iterators returned by iter() in 3.x are dict_keyiterator, dict_itemiterator, and dict_valueiterator.

关于python - 在计算 networkx 中的传出和传入边缘时,len 抛出 'dict_keyiterator' 没有 len(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53584341/

相关文章:

python-3.x - 如何获得networkx中无向边的权重?

python - 如何在 BeautifulSoup 中得到想要的值?

python - 从html中提取数组元素

python - 无法在 Windows ubuntu 上的 python 中安装模式模块

python - 如何使用嵌套循环为函数设置动画?

python - Python 百分位数函数

python - networkx 在左侧和右侧绘制单独的节点 - graphviz,python

python - 如何在 Keras python 中输入 LSTM 模型?

python - 解包元组列表的 dask 延迟对象

python - Networkx 中的传递闭包