iter,值,字典中的项不

2024-04-25 13:38:05 发布

您现在位置:Python中文网/ 问答频道 /正文

拥有这个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。。。但那不管用 如何修改代码?


Tags: 代码intreeifrootcurrentoutgraph
1条回答
网友
1楼 · 发布于 2024-04-25 13:38:05

您正在使用Python 3;请改用dict.items()

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

Python 3 What's New documentation

  • dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).
  • Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.

此外,.next()方法已重命名为.__next__(),但字典视图不是迭代器。必须将graph.iteritems().next()行翻译为:

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

它使用iter()将items视图转换为iterable,并使用next()从iterable获取下一个值。

您还必须重命名while循环中的next变量;使用该变量替换此处需要的内置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]}

相关问题 更多 >