拥有这个python代码
edges = [(0, [3]), (1, [0]), (2, [1, 6]), (3, [2]), (4, [2]), (5, [4]), (6, [5, 8]), (7, [9]), (8, [7]), (9, [6])]
graph = {0: [3], 1: [0], 2: [1, 6], 3: [2], 4: [2], 5: [4], 6: [5, 8], 7: [9], 8: [7], 9: [6]}
cycles = {}
while graph:
current = graph.iteritems().next()
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)
def traverse(tree, root):
out = []
for r in tree[root]:
if r != root and r in tree:
out += traverse(tree, r)
else:
out.append(r)
return out
print ('->'.join([str(i) for i in traverse(cycles, 0)]))
Traceback (most recent call last):
File "C:\Users\E\Desktop\c.py", line 20, in <module>
current = graph.iteritems().next()
AttributeError: 'dict' object has no attribute 'iteritems'
我也试过itervalues,iterkeys。。。但那不管用 如何修改代码?
您正在使用Python 3;请改用
dict.items()
。Python 2
dict.iter*
方法已在Python 3中重命名,其中dict.items()
现在默认返回字典视图而不是列表。字典视图的作用与Python 2中的dict.iteritems()
相同。从Python 3 What's New documentation:
此外,
.next()
方法已重命名为.__next__()
,但字典视图不是迭代器。必须将graph.iteritems().next()
行翻译为:它使用
iter()
将items视图转换为iterable,并使用next()
从iterable获取下一个值。您还必须重命名
while
循环中的next
变量;使用该变量替换此处需要的内置next()
函数。改用next_
。下一个问题是您试图使用
current
作为cycles
中的键,但是current
是整数的元组和整数的列表,这使得整个值不可哈希。我认为你只想得到下一个键,在这种情况下next(iter(dict))
会给你:然后产生一些输出:
相关问题 更多 >
编程相关推荐