zoukankan      html  css  js  c++  java
  • 文档翻译 Python 2.7.x和Python 3.x之间的主要区别(包括示例)

    许多Python初学者都想知道应该从哪个版本的Python开始。我对这个问题的回答通常是“仅需使用您喜欢的教程所写的版本,并在以后查看差异”。

    但是,如果您开始一个新项目并可以选择,该怎么办?我要说的是,只要Python 2.7.x和Python 3.x都支持您计划使用的库,那么目前就没有“对”或“错”。但是,这两个最受欢迎的Python版本之间的主要区别值得一看,以此避免在为其中任何一个编写代码或计划移植项目时遇见陷阱。

     

    __future__模块

    Python 3.x引入了一些Python 2不兼容的关键字和功能,可以通过__future__Python 2 的内置模块导入这些关键字和功能。__future__如果您打算为代码提供Python 3.x支持,建议使用import导入。例如,如果我们想要Python 2中Python 3.x的整数除法行为,则可以通过以下方式将其导入

    from __future__ import division

    __future__下表列出了可以从模块导入的更多功能:

    特征可选(版本)强制(版本)影响
    nested_scopes 2.1.0b1 2.2 PEP 227静态嵌套的合并范围
    generators 2.2.0a1 2.3 PEP 255简单生成器
    division 2.2.0a2 3.0 PEP 238更改除法运算符
    absolute_import 2.5.0a1 3.0 PEP 328导入:多行和绝对/相对
    with_statement 2.5.0a1 2.6 PEP 343“ with”声明
    print_function 2.6.0a2 3.0 PEP 3105使打印功能
    unicode_literals 2.6.0a2 3.0 PEP 3112Python 3000中的字节字面量

    (来源:[https://docs.python.org/2/library/__future__.html](https://docs.python.org/2/library/__future__.html#module-__future__))

    from platform import python_version

    打印功能

    非常琐碎,并且print语法中的更改可能是最广为人知的更改,但仍然值得一提:Python 2的print语句已被该print()函数替换,这意味着我们必须把要打印的对象包装在括号中。

    如果我们用Python 2的不带括号的方式调用print功能, Python 2不会出现其他额外问题,但是相反,Python 3会抛出一个SyntaxError

    Python 2

    print 'Python', python_version()
    print 'Hello, World!'
    print('Hello, World!')
    print "text", ; print 'print more text on the same line'
    Python 2.7.6
    Hello, World!
    Hello, World!
    text print more text on the same line

    Python 3

    print('Python', python_version())
    print('Hello, World!')

    print("some text,", end="")
    print(' print more text on the same line')
    Python 3.4.1
    Hello, World!
    some text, print more text on the same line
    print 'Hello, World!'
    File "<ipython-input-3-139a7c5835bd>", line 1
      print 'Hello, World!'
                          ^
    SyntaxError: invalid syntax

    注意:

    通过Python 2在上面打印“ Hello,World”看起来很“正常”。但是,如果在括号内有多个对象,则将创建一个元组,因为这个print在Python 2中是“语句”,而不是函数调用。

    print 'Python', python_version()
    print('a', 'b')
    print 'a', 'b'
    Python 2.7.7
    ('a', 'b')
    a b

    整数除法

    如果您正在移植代码,或者您正在Python 2中执行Python 3代码,则此更改特别危险,因为整数除法行为的更改通常不会引起注意(它不会引发SyntaxError)。 因此,我仍然倾向于在我的Python 3脚本中使用float(3)/23/2.0代替a 3/2,以免给Python 2带来麻烦(反之亦然,我建议在您的Python 2脚本中使用from __future__ import division )。

    Python 2

    print 'Python', python_version()
    print '3 / 2 =', 3 / 2
    print '3 // 2 =', 3 // 2
    print '3 / 2.0 =', 3 / 2.0
    print '3 // 2.0 =', 3 // 2.0
    Python 2.7.6
    3 / 2 = 1
    3 // 2 = 1
    3 / 2.0 = 1.5
    3 // 2.0 = 1.0

    Python 3

    print('Python', python_version())
    print('3 / 2 =', 3 / 2)
    print('3 // 2 =', 3 // 2)
    print('3 / 2.0 =', 3 / 2.0)
    print('3 // 2.0 =', 3 // 2.0)
    Python 3.4.1
    3 / 2 = 1.5
    3 // 2 = 1
    3 / 2.0 = 1.5
    3 // 2.0 = 1.0

    Unicode

    Python 2具有ASCII str()类型,独有类型unicode(),但没有byte类型。

    现在,在Python 3中,我们终于有了Unicode(utf-8)strings和2个字节的类:bytebytearray

    Python 2

    print 'Python', python_version()
    Python 2.7.6
    print type(unicode('this is like a python3 str type'))
    <type 'unicode'>
    print type(b'byte type does not exist')
    <type 'str'>
    print 'they are really' + b' the same'
    they are really the same
    print type(bytearray(b'bytearray oddly does exist though'))
    <type 'bytearray'>

    Python 3

    print('Python', python_version())
    print('strings are now utf-8 u03BCnicou0394é!')
    Python 3.4.1
    strings are now utf-8 μnicoΔé!
    print('Python', python_version(), end="")
    print(' has', type(b' bytes for storing data'))
    Python 3.4.1 has <class 'bytes'>
    print('and Python', python_version(), end="")
    print(' also has', type(bytearray(b'bytearrays')))
    and Python 3.4.1 also has <class 'bytearray'>
    'note that we cannot add a string' + b'bytes for data'
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)

    <ipython-input-13-d3e8942ccf81> in <module>()
    ----> 1 'note that we cannot add a string' + b'bytes for data'


    TypeError: Can't convert 'bytes' object to str implicitly

    Xrange

    在Python 2.x中,用xrange()在创建可迭代对象非常流行(例如在for循环或list / set-dictionary-comprehension 中)。 该行为与生成器非常相似(即“惰性求值”),但是这里的xrange-iterable不是穷举的--这意味着,您可以对其进行无限迭代。

    由于其“惰性求值”,range()的常规优势在于,如果您只需要对其进行一次迭代(例如,在for循环中),通常xrange()更快。但是,与一次迭代相反,这里不建议重复多次,因为每次生成都是从头开始的!

    在Python 3中,range()的实现类似于xrange()函数,因此xrange()不再是专有函数(在Python 3中xrange()引发了NameError)。

    import timeit

    n = 10000
    def test_range(n):
      return for i in range(n):
          pass

    def test_xrange(n):
      for i in xrange(n):
          pass    

    Python 2

    print 'Python', python_version()

    print ' timing range()'
    %timeit test_range(n)

    print ' timing xrange()'
    %timeit test_xrange(n)
    Python 2.7.6

    timing range()
    1000 loops, best of 3: 433 µs per loop


    timing xrange()
    1000 loops, best of 3: 350 µs per loop

    Python 3

    print('Python', python_version())

    print(' timing range()')
    %timeit test_range(n)
    Python 3.4.1

    timing range()
    1000 loops, best of 3: 520 µs per loop
    print(xrange(10))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)

    <ipython-input-5-5d8f9b79ea70> in <module>()
    ----> 1 print(xrange(10))


    NameError: name 'xrange' is not defined

     

    Python 3中range对象的__contains__方法

    值得一提的另一件事是在Python 3.x 中range有了一个“新” __contains__方法(感谢Yuchen Ying指出了这一点)。对于整数和布尔类型,该__contains__方法可以大大加快Python 3.x中range的“查找”速度。

    x = 10000000
    def val_in_range(x, val):
      return val in range(x)
    def val_in_xrange(x, val):
      return val in xrange(x)
    print('Python', python_version())
    assert(val_in_range(x, x/2) == True)
    assert(val_in_range(x, x//2) == True)
    %timeit val_in_range(x, x/2)
    %timeit val_in_range(x, x//2)
    Python 3.4.1
    1 loops, best of 3: 742 ms per loop
    1000000 loops, best of 3: 1.19 µs per loop

    根据上面的timeit结果,您可以看到当“查找”的执行对象是整数类型而不是浮点型时,执行速度提高了约60,000。但是,由于Python 2.x rangexrange没有__contains__方法,整数或浮点数的“查找速度”不会有太大不同:

    print 'Python', python_version()
    assert(val_in_xrange(x, x/2.0) == True)
    assert(val_in_xrange(x, x/2) == True)
    assert(val_in_range(x, x/2) == True)
    assert(val_in_range(x, x//2) == True)
    %timeit val_in_xrange(x, x/2.0)
    %timeit val_in_xrange(x, x/2)
    %timeit val_in_range(x, x/2.0)
    %timeit val_in_range(x, x/2)
    Python 2.7.7
    1 loops, best of 3: 285 ms per loop
    1 loops, best of 3: 179 ms per loop
    1 loops, best of 3: 658 ms per loop
    1 loops, best of 3: 556 ms per loop

    在该__contain__方法尚未添加到Python 2.x 的“proofs”之下:

    print('Python', python_version())
    range.__contains__
    Python 3.4.1





    <slot wrapper '__contains__' of 'range' objects>
    print 'Python', python_version()
    range.__contains__
    Python 2.7.7



    ---------------------------------------------------------------------------
    AttributeError                           Traceback (most recent call last)

    <ipython-input-7-05327350dafb> in <module>()
        1 print 'Python', python_version()
    ----> 2 range.__contains__


    AttributeError: 'builtin_function_or_method' object has no attribute '__contains__'
    print 'Python', python_version()
    xrange.__contains__
    Python 2.7.7



    ---------------------------------------------------------------------------
    AttributeError                           Traceback (most recent call last)

    <ipython-input-8-7d1a71bfee8e> in <module>()
        1 print 'Python', python_version()
    ----> 2 xrange.__contains__


    AttributeError: type object 'xrange' has no attribute '__contains__'

    注意Python 2和3中的速度差异

    有人指出Python 3 range()和Python2 xrange()之间的速度差异。由于它们以相同的方式实现,因此期望速度相同, 然而,确实存在的区别在于Python 3通常比Python 2的运行速度慢。

    def test_while():
      i = 0
      while i < 20000:
          i += 1
      return
    print('Python', python_version())
    %timeit test_while()
    Python 3.4.1
    100 loops, best of 3: 2.68 ms per loop
    print 'Python', python_version()
    %timeit test_while()
    Python 2.7.6
    1000 loops, best of 3: 1.72 ms per loop

    引发异常

    在Python 2接受“旧”和“新”两种表示法的情况下,如果我们不将异常参数括在括号中,则Python 3会阻塞(并引发一个SyntaxError的返回):

    Python 2

    print 'Python', python_version()
    Python 2.7.6
    raise IOError, "file error"
    ---------------------------------------------------------------------------
    IOError                                   Traceback (most recent call last)

    <ipython-input-8-25f049caebb0> in <module>()
    ----> 1 raise IOError, "file error"


    IOError: file error
    raise IOError("file error")
    ---------------------------------------------------------------------------
    IOError                                   Traceback (most recent call last)

    <ipython-input-9-6f1c43f525b2> in <module>()
    ----> 1 raise IOError("file error")


    IOError: file error

    Python 3

    print('Python', python_version())
    Python 3.4.1
    raise IOError, "file error"
    File "<ipython-input-10-25f049caebb0>", line 1
      raise IOError, "file error"
                    ^
    SyntaxError: invalid syntax

    在Python 3中引发异常的正确方法:

    print('Python', python_version())
    raise IOError("file error")
    Python 3.4.1



    ---------------------------------------------------------------------------
    OSError                                   Traceback (most recent call last)

    <ipython-input-11-c350544d15da> in <module>()
        1 print('Python', python_version())
    ----> 2 raise IOError("file error")


    OSError: file error

    处理异常

    另外,在Python 3中对异常的处理也略有变化。在Python 3中,我们现在必须使用“ as”关键字

    Python 2

    print 'Python', python_version()
    try:
      let_us_cause_a_NameError
    except NameError, err:
      print err, '--> our error message'
    Python 2.7.6
    name 'let_us_cause_a_NameError' is not defined --> our error message

    Python 3

    print('Python', python_version())
    try:
      let_us_cause_a_NameError
    except NameError as err:
      print(err, '--> our error message')
    Python 3.4.1
    name 'let_us_cause_a_NameError' is not defined --> our error message

     

    next()函数和.next()方法

    鉴于next().next())是一种如此常用的函数(方法),故值得一提的是另一种语法更改(或更确切地说是实现上的更改):在Python 2.7.5中可以同时使用函数和方法,该next()函数就是仍保留在Python 3中(调用.next()方法会引发AttributeError)。(本段待修正--译者按)

    Python 2

    print 'Python', python_version()

    my_generator = (letter for letter in 'abcdefg')

    next(my_generator)
    my_generator.next()
    Python 2.7.6





    'b'

    Python 3

    print('Python', python_version())

    my_generator = (letter for letter in 'abcdefg')

    next(my_generator)
    Python 3.4.1





    'a'
    my_generator.next()
    ---------------------------------------------------------------------------
    AttributeError                           Traceback (most recent call last)

    <ipython-input-14-125f388bb61b> in <module>()
    ----> 1 my_generator.next()


    AttributeError: 'generator' object has no attribute 'next'

    For循环变量和全局名称空间泄漏

    好消息是:在Python 3.x中,for循环变量不再泄漏到全局名称空间中!

    这可以追溯到在Python 3.x中所做的更改,并在Python 3.0的新增功能中进行了如下描述:

     

    "列表理解不再支持语法形式[... for var in item1, item2, ...]。使用[... for var in (item1, item2, ...)]代替。还要注意,列表理解具有不同的语义:对于list()构造函数内部的生成器表达式,它们更接近语法糖,并且尤其是循环控制变量不再泄漏到周围的范围中。"

    Python 2

    print 'Python', python_version()

    i = 1
    print 'before: i =', i

    print 'comprehension: ', [i for i in range(5)]

    print 'after: i =', i
    Python 2.7.6
    before: i = 1
    comprehension: [0, 1, 2, 3, 4]
    after: i = 4

    Python 3

    print('Python', python_version())

    i = 1
    print('before: i =', i)

    print('comprehension:', [i for i in range(5)])

    print('after: i =', i)
    Python 3.4.1
    before: i = 1
    comprehension: [0, 1, 2, 3, 4]
    after: i = 1

    比较无序类型

    Python 3的另一个不错的变化是,如果我们尝试比较无序类型,则会引发TypeError警告。

    Python 2

    print 'Python', python_version()
    print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
    print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
    print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)
    Python 2.7.6
    [1, 2] > 'foo' = False
    (1, 2) > 'foo' = True
    [1, 2] > (1, 2) = False

    Python 3

    print('Python', python_version())
    print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
    print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
    print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
    Python 3.4.1



    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)

    <ipython-input-16-a9031729f4a0> in <module>()
        1 print('Python', python_version())
    ----> 2 print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
        3 print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
        4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))


    TypeError: unorderable types: list() > str()

     

    通过input()解析用户输入

    幸运的是,该input()函数已在Python 3中修复,因此它始终将用户输入存储为str对象。为了避免在Python 2中使用strings以外的其他类型进行读取的危险行为,我们必须改变raw_input()的使用。

    Python 2

    Python 2.7.6
    [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.

    >>> my_input = input('enter a number: ')

    enter a number: 123

    >>> type(my_input)
    <type 'int'>

    >>> my_input = raw_input('enter a number: ')

    enter a number: 123

    >>> type(my_input)
    <type 'str'>

    Python 3

    Python 3.4.1
    [GCC 4.2.1 (Apple Inc. build 5577)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.

    >>> my_input = input('enter a number: ')

    enter a number: 123

    >>> type(my_input)
    <class 'str'>

    返回可迭代对象而不是列表

    如本xrange节所述,一些函数和方法现在在Python 3中返回可迭代对象-而不是Python 2中的列表。

    由于我们通常只迭代一次,因此我认为这种更改在节省内存方面很有意义。但是,与生成器相比,如果需要的话,也有可能迭代多次,至于此这并不是那么有效。

    对于那些我们确实需要list-objects的情况,我们可以简单的通过list()函数将可迭代对象转换为list

    Python 2

    print 'Python', python_version()

    print range(3)
    print type(range(3))
    Python 2.7.6
    [0, 1, 2]
    <type 'list'>

    Python 3

    print('Python', python_version())

    print(range(3))
    print(type(range(3)))
    print(list(range(3)))
    Python 3.4.1
    range(0, 3)
    <class 'range'>
    [0, 1, 2]

    Python 3中一些不再返回列表的更常用的函数和方法:

    • zip()

    • map()

    • filter()

    • 字典的.keys()方法

    • 字典的.values()方法

    • 字典的.items()方法

    银行家算法(四舍六入五成双:译者按)

    当Python 3在最后一个有效数字处产生并列(.5)时,Python 3采用了现在的四舍五入方式。现在,在Python 3中,小数点将四舍五入为最接近的偶数。尽管这对于代码可移植性带来了不便,但是与四舍五入相比,它被认为是一种更好的舍入方式,因为它避免了偏向大数的情况。有关更多信息,请参见优秀的的Wikipedia文章和段落:

    Python 2

    print 'Python', python_version()
    Python 2.7.12
    round(15.5)
    16.0
    round(16.5)
    17.0

    Python 3

    print('Python', python_version())
    Python 3.5.1
    round(15.5)
    16
    round(16.5)
    16

     

     

    原文链接:  https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#more-articles-about-python-2-and-python-3

    作者:塞巴斯蒂安·拉施卡(Sebastian Raschka)

    翻译:  墨寒

  • 相关阅读:
    [windows] gcc编译器
    [windos] 命令
    软件版本命名规范
    [linux] vim 编辑器---更改注释文字颜色
    Call Indels/SV常用软件-搬运工
    [生物信息比对软件列表]
    [samtools] 文本查看语法,浏览SNP/INDEL位点
    [python] 之 异常对象
    [python] 之 类-运算符重载
    [R] 之 管理工作空间函数
  • 原文地址:https://www.cnblogs.com/hello-bug/p/11630728.html
Copyright © 2011-2022 走看看