栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Iter,值,字典中的项目不起作用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Iter,值,字典中的项目不起作用

您正在使用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()))

它用于

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]}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640386.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号