您正在使用Python 3;使用
dict.items()代替。
Python 2
dict.iter*方法已在Python
3中重命名,该方法
dict.items()现在默认返回字典视图而不是列表。字典视图的可迭代性与
dict.iteritems()Python
2中的可迭代性相同。
来自Python 3新增功能文档:
*
dict方法dict.keys(),dict.items()然后dict.values()返回“视图”而不是列表。例如,它不再起作用:k= d.keys(); k.sort()。使用k = sorted(d)代替(这也适用于Python 2.5,并且同样有效)。
* 此外,dict.iterkeys(),dict.iteritems()并dict.itervalues()不再支持的方法。
同样,该
.next()方法已重命名为
.__next__(),但是字典视图不是迭代器。该行
graph.iteritems().next()必须改为翻译为:
current = next(iter(graph.items()))
它用于
iter()将项目视图变成一个可迭代的对象,并
next()从该可迭代对象中获取下一个值。
您还必须
next在
while循环中重命名变量。使用该功能替换
next()您在此处需要的内置功能。使用
next_代替。
下一个问题是您试图
current用作中的键
cycles,但是它
current是一个整数的元组和一个整数 列表 ,从而使整个值不可散列。我
认为 您只想获取下一个 密钥 ,在这种情况下
next(iter(dict)),您会得到:
while graph: current = next(iter(graph)) cycle = [current] cycles[current] = cycle while current in graph: next_ = graph[current][0] del graph[current][0] if len(graph[current]) == 0: del graph[current] current = next_ cycle.append(next_)
然后产生一些输出:
>>> cycles{0: [0, 3, 2, 1, 0], 2: [2, 6, 5, 4, 2], 6: [6, 8, 7, 9, 6]}


