拥有这个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 2dict.iter*方法已经在python 3中被重命名,在这里dict.items()现在默认返回字典视图而不是列表。字典视图在python 2中的作用与iterables相同。
Python 3 What's New documentation开始:
dict.iteritems()methodsdictdict.keys()anddict.items()return“views”而不是list。例如,这不再有效:dict.values()。使用k = d.keys(); k.sort()代替(这同样适用于python 2.5,而且也同样有效)。
此外,不再支持k = sorted(d)dict.iterkeys()dict.iteritems()方法。
此外,dict.itervalues()方法已重命名为.next(),但字典视图不是迭代器。行.__next__()必须转换为:

current = next(iter(graph.items()))

它使用graph.iteritems().next()将items视图转换为iterable,并使用iter()从iterable获取下一个值。
您还必须重命名next()循环中的next变量;使用该变量替换您在此需要的内置while函数。使用next()代替。
下一个问题是,您试图使用next_作为current中的键,但cycles是一个整数和整数列表的元组,使整数值不可哈希。我认为你只想得到下一个键,在这种情况下,current会给你:
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]}

10-07 19:12
查看更多