计算networkx中的传出和传入边缘时,带有'dict_keyiterator'的len throws没有len() [英] len throws with 'dict_keyiterator' has no len() when calculating outgoing and incoming edges in networkx

查看:866
本文介绍了计算networkx中的传出和传入边缘时,带有'dict_keyiterator'的len throws没有len()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am implementing a graph manipulation script and I was puzzled with the following error:

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,以及如何修复我的代码?谢谢!

What is this dict_keyiterator and how to fix my code? Thanks!

推荐答案

该问题最终可以通过将迭代器转换为列表来解决:

The issue was eventually fixable by converting the iterator to a list:

print(len(list(graph.predecessors(i))), len(list(graph.successors(i))))

正如Yakym Pirozhenko所建议的那样,提出了一种替代方法,该方法被认为更快,因此我进行了检查:

As suggested by Yakym Pirozhenko suggested an alternative approach deemed faster so I checked:

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.

Clearly, the len(list(...)) approach is faster here. I was using: Python 3.7 on Windows 10.

经过一番搜索,我发现了一个问题,其中有一个类似问题,而且很简单说明此处:

After some searching I have found a question with a similar problem and a straightforward explanation here:

在2.x版本中,iter(some_dict)返回一个字典keyiterator(很奇怪 连字号).在3.x中,它是dict_keyiterator(正常的下划线).

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会导致Python 3中的对象类型为dict_keyiterator.这是替换Python 2的3个迭代器之一:d.viewkeys()d.viewitems()d.viewvalues():

So it seems that direct use of iter(d) where d is a dict results in the object of type dict_keyiterator in Python 3. This is one of 3 iterators replacing Python 2: d.viewkeys(), d.viewitems(), and d.viewvalues():

3.x中iter()返回的相应迭代器为 dict_keyiteratordict_itemiteratordict_valueiterator.

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

这篇关于计算networkx中的传出和传入边缘时,带有'dict_keyiterator'的len throws没有len()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆