在 Python 2 中使用 Python 3 样式集

Use Python 3-styled sets in Python 2

在 Python 3 中,集合表示法更接近集合在集合论中的表示方式,而 Python 2 使用列表样式(即 set_py3 = {"A","B","C"} \ set_py2 = set(["A","B","C"]))

有什么方法可以使用 from __future__ 将集合表示法从 Python 3 移植到 Python 2?

Py2.7 让我们使用 {"A","B","C"} 集合符号,但当它被打印时,它仍然是 set(["A","B","C"]) 。我看到了 from __future__ import braces 但我不认为它引入了这种类型的集合表示法。我知道您可以使用 from __future__ import print_function 导入新的打印功能。我不确定是否有类似的方法来移植集合符号。

有一些特性ported to Python 2.7 from 3.1,包括集合表达式语法;和其他事情:

Much as Python 2.6 incorporated features from Python 3.0, version 2.7 incorporates some of the new features in Python 3.1. The 2.x series continues to provide tools for migrating to the 3.x series.

A partial list of 3.1 features that were backported to 2.7:

  • The syntax for set literals ({1,2,3} is a mutable set).
  • Dictionary and set comprehensions ({i: i*2 for i in range(3)}).
  • Multiple context managers in a single with statement.
  • A new version of the io library, rewritten in C for performance.
  • The ordered-dictionary type described in PEP 372: Adding an Ordered Dictionary to collections.
  • The new "," format specifier described in PEP 378: Format Specifier for Thousands Separator.
  • The memoryview object.
  • ...

因此,要使用新语法,只需升级到 Python 2.7