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

时间:2013-12-07 17:32:14

标签: 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'

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

1 个答案:

答案 0 :(得分:33)

您使用的是Python 3;请改用dict.items()

Python 2 dict.iter*方法已在Python 3中重命名,其中dict.items()现在默认返回字典视图而不是列表。字典视图以与Python 2中dict.iteritems()相同的方式充当迭代。

来自Python 3 What's New documentation

  
      
  • 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]}
相关问题