为什么 Python 3 需要用 list() 包装 dict.items? [英] Why does Python 3 need dict.items to be wrapped with list()?

查看:35
本文介绍了为什么 Python 3 需要用 list() 包装 dict.items?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 3.我刚刚安装了一个 Python IDE,我对以下代码警告很好奇:

I'm using Python 3. I've just installed a Python IDE and I am curious about the following code warning:

features = { ... }
for k, v in features.items():
    print("%s=%s" % (k, v))

警告是:对于 Python3 的支持应该看起来像 ... list(features.items())"

http://docs.python.org 上也提到了这一点/2/library/2to3.html#fixers

它还在对 list 的调用中封装了 dict.items()、dict.keys() 和 dict.values() 的现有用法.

It also wraps existing usages of dict.items(), dict.keys(), and dict.values() in a call to list.

为什么需要这样做?

推荐答案

您可以放心地忽略这个额外的预防措施"警告:即使没有 list正常工作> 在两个版本的 Python 中.如果您需要一个列表,它会以不同的方式运行(但事实并非如此):事实上,features.items() 在 Python 2 中是一个 list,但是 features.items() 是一个 listem>view 在 Python 3 中.他们工作用作可迭代对象时相同,如您的示例所示.

You can safely ignore this "extra precautions" warning: your code will work the same even without list in both versions of Python. It would run differently if you needed a list (but this is not the case): in fact, features.items() is a list in Python 2, but a view in Python 3. They work the same when used as an iterable, as in your example.

现在,Python 2 到 Python 3 的转换工具 2to3 在安全方面犯了错误,并假设您在使用 dict 时确实想要一个 list.items().情况可能并非如此(如问题中所述),在这种情况下,Python 3 中的 dict.items()(不包装 list)更好(更快,更少内存消耗,因为没有建立列表).

Now, the Python 2 to Python 3 conversion tool 2to3 errs on the side of safety, and assumes that you really wanted a list when you use dict.items(). This may not be the case (as in the question), in which case dict.items() in Python 3 (no wrapping list) is better (faster, and less memory-consuming, since no list is built).

具体来说,这意味着 Python 2 代码可以显式迭代视图:for k, v in features.viewitems()(在 Python 3 中将通过 2to3 进行转换)code> 到 features.items()).看起来你的 IDE 认为代码是 Python 2,因为你的 for 语句非常好,在 Python 3 中,所以应该没有关于 Python 3 支持的警告.

Concretely, this means that Python 2 code can explicitly iterate over the view: for k, v in features.viewitems() (which will be converted in Python 3 by 2to3 to features.items()). It looks like your IDE thinks that the code is Python 2, because your for statement is very good, in Python 3, so there should be no warning about Python 3 support.

这篇关于为什么 Python 3 需要用 list() 包装 dict.items?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆