Python 2中的Python 3 dict行为 [英] Python 3 dict behavior in Python 2

查看:64
本文介绍了Python 2中的Python 3 dict行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个问题.在此之前,我从未听说过future_builtins,这让我感到奇怪. future_builtins仅涵盖几种类型,而dict不是其中一种.有没有一种方法可以使用Python 3 dict行为,该行为在Python 2.7中使用itemskeysvalues的视图?在尝试编写与Python 3兼容的代码时,这将特别有用.在Python 2中,这些方法具有创建list的开销,而迭代器版本在Python 3中已消失.但是建议使用它们来编写与Python 3兼容的代码.

I saw this question tonight. I had never heard of future_builtins before this, and it got me wondering. future_builtins only covers a few types, and dict is not one of them. Is there a way to use the Python 3 dict behavior that uses views for items, keys, and values in Python 2.7? This would be especially useful when trying to write Python 3 compatible code. In Python 2, these methods have the overhead of creating lists, and the iterator versions go away in Python 3. Yet using them is the recommendation for writing Python 3 compatible code.

推荐答案

您可以在py2x中使用viewkeys()viewitems()viewvalues().

You can use viewkeys(), viewitems() and viewvalues() in py2x.

>>> dict.viewkeys?
Type:       method_descriptor
String Form:<method 'viewkeys' of 'dict' objects>
Namespace:  Python builtin
Docstring:  D.viewkeys() -> a set-like object providing a view on D's keys

Python 3.0的新增功能:

  • dict方法dict.keys()dict.items()dict.values()返回视图"而不是列表.例如,这不再起作用:k = d.keys(); k.sort().改为使用k = sorted(d)(这也适用于Python 2.5,并且同样有效).
  • 此外,不再支持dict.iterkeys()dict.iteritems()dict.itervalues()方法.
  • 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.

错误:将dictviews移植到2.7 :

与圭多交谈后,摆脱了未来进口魔术的青睐 只提供viewkeysviewitemsviewvalues方法的 字典.这样可以通过以下方式高效地使用2.6和3.0 dict代码 使2to3view方法直接转换为keys/values/items 在 3.0,而不是将所有内容都包装在list()中.

After talking to Guido, got rid of the future import magic in favour of just providing viewkeys, viewitems and viewvalues methods of dicts. This makes efficient 2.6-and-3.0 dict-using code possibly by making 2to3 translate the view-methods directly to keys/values/items in 3.0, and not wrapping everything in list().

2to3工具:

RefactoringTool: Refactored so.py
--- so.py   (original)
+++ so.py   (refactored)
@@ -1 +1 @@
-print dic.viewkeys()
+print(dic.keys())

这篇关于Python 2中的Python 3 dict行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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