iter,values,字典中的项目不起作用

cMi*_*nor 15 python dictionary

有这个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'
Run Code Online (Sandbox Code Playgroud)

我也试过itervalues,iterkeys ......但这不起作用如何修改代码?

Mar*_*ers 35

你正在使用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()))
Run Code Online (Sandbox Code Playgroud)

它使用iter()打开物品查看到迭代和next()获取来自可迭代的下一个值.

您还必须nextwhile循环中重命名变量; 使用它取代了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_)
Run Code Online (Sandbox Code Playgroud)

然后产生一些输出:

>>> cycles
{0: [0, 3, 2, 1, 0], 2: [2, 6, 5, 4, 2], 6: [6, 8, 7, 9, 6]}
Run Code Online (Sandbox Code Playgroud)