问题描述
有这个python代码
Having this python code
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 ...但是不起作用
如何修改代码?
I also tried itervalues, iterkeys... but that does not workHow to modify code?
推荐答案
您正在使用Python 3;使用 dict.items()
You are using Python 3; use dict.items()
instead.
Python 2 dict.iter * / code>方法已经在Python 3中重命名,其中
dict.items()
默认情况下返回字典视图而不是列表。字典视图以与Python 2相同的方式 dict.iteritems()
做为迭代。
The Python 2 dict.iter*
methods have been renamed in Python 3, where dict.items()
returns a dictionary view instead of a list by default now. Dictionary views act as iterables in the same way dict.iteritems()
do in Python 2.
从 Python 3最新的文档:
另外, .next()
方法已重命名为 .__ next __()
,但字典视图不是迭代器。必须将 graph.iteritems()。next()
的行转换为:
Also, the .next()
method has been renamed to .__next__()
, but dictionary views are not iterators. The line graph.iteritems().next()
would have to be translated instead, to:
current = next(iter(graph.items()))
使用 iter()
将项目视图转换为可迭代的 next()
以从该可迭代中获取下一个值
which uses iter()
to turn the items view into an iterable and next()
to get the next value from that iterable.
您还必须在中重命名
下一个
变量,而 loop;使用它取代了你在这里需要的内置
next()
函数。使用下一个_
。
You'll also have to rename the next
variable in the while
loop; using that replaces the built-in next()
function which you need here. Use next_
instead.
下一个问题是您正在尝试使用 current
作为循环
中的键,但当前
是整数和列表的整数,使整个值不可哈希。我想你想要获得下一个键,在这种情况下, next(iter(dict))
给你:
The next problem is that you are trying to use current
as a key in cycles
, but current
is a tuple of an integer and a list of integers, making the whole value not hashable. I think you wanted to get just the next key instead, in which case next(iter(dict))
would give you that:
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]}
这篇关于iter,值,字典中的项不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!