Python 2.7.x 和 3.x 版本的重要区别小结

许多Python初学者都会问:我应该学习哪个版本的Python。对于这个问题,我的回答通常是“先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本。等学得差不多了,再来研究不同版本之间的差别”。

但如果想要用Python开发一个新项目,那么该如何选择Python版本呢?我可以负责任的说,大部分Python库都同时支持Python 2.7.x和3.x版本的,所以不论选择哪个版本都是可以的。但为了在使用Python时避开某些版本中一些常见的陷阱,或需要移植某个Python项目时,依然有必要了解一下Python两个常见版本之间的主要区别。

目录

  • 使用__future__模块
  • print函数
  • 整数除法
  • Unicode
  • xrange
  • 触发异常
  • 处理异常
  • next()函数和.next()方法
  • For循环变量与全局命名空间泄漏
  • 比较无序类型
  • 使用input()解析输入内容
  • 返回可迭代对象,而不是列表
  • 更多关于Python 2和Python 3的文章

__future__模块

[回到目录]

Python 3.x引入了一些与Python 2不兼容的关键字和特性,在Python 2中,可以通过内置的__future__模块导入这些新内容。如果你希望在Python 2环境下写的代码也可以在Python 3.x中运行,那么建议使用__future__模块。例如,如果希望在Python 2中拥有Python 3.x的整数除法行为,可以通过下面的语句导入相应的模块。

from __future__ import division

下表列出了__future__中其他可导入的特性:

特性 可选版本 强制版本 效果
nested_scopes 2.1.0b1 2.2 PEP 227:
Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255:
Simple Generators
division 2.2.0a2 3.0 PEP 238:
Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328:
Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343:
The “with” Statement
print_function 2.6.0a2 3.0 PEP 3105:
Make print a function
unicode_literals 2.6.0a2 3.0 PEP 3112:
Bytes literals in Python 3000

(来源: https://docs.python.org/2/library/future.html)

示例:

from platform import python_version

print函数

[回到目录]

虽然print语法是Python 3中一个很小的改动,且应该已经广为人知,但依然值得提一下:Python 2中的print语句被Python 3中的print()函数取代,这意味着在Python 3中必须用括号将需要输出的对象括起来。

在Python 2中使用额外的括号也是可以的。但反过来在Python 3中想以Python2的形式不带括号调用print函数时,会触发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中,带不带括号输出”Hello World”都很正常。但如果在圆括号中同时输出多个对象时,就会创建一个元组,这是因为在Python 2中,print是一个语句,而不是函数调用。

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

整数除法

[回到目录]

由于人们常常会忽视Python 3在整数除法上的改动(写错了也不会触发Syntax Error),所以在移植代码或在Python 2中执行Python 3的代码时,需要特别注意这个改动。

所以,我还是会在Python 3的脚本中尝试用float(3)/2或 3/2.0代替3/2,以此来避免代码在Python 2环境下可能导致的错误(或与之相反,在Python 2脚本中用from __future__ import division来使用Python 3的除法)。

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()函数转成unicode类型,但没有byte类型。

而在Python 3中,终于有了Unicode(utf-8)字符串,以及两个字节类:bytes和bytearrays。

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循环”或“列表/集合/字典推导式”中。

这种行为与生成器非常相似(如”惰性求值“),但这里的xrange-iterable无尽的,意味着可能在这个xrange上无限迭代。

由于xrange的“惰性求知“特性,如果只需迭代一次(如for循环中),range()通常比xrange()快一些。不过不建议在多次迭代中使用range(),因为range()每次都会在内存中重新生成一个列表。

在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 'ntiming range()'
%timeit test_range(n)

print 'nntiming 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('ntiming 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)
in ()
----> 1 print(xrange(10))

NameError: name 'xrange' is not defined

Python 3中的range对象中的__contains__方法

另一个值得一提的是,在Python 3.x中,range有了一个新的__contains__方法。__contains__方法可以有效的加快Python 3.x中整数和布尔型的“查找”速度。

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的结果,查找整数比查找浮点数要快大约6万倍。但由于Python 2.x中的range或xrange没有__contains__方法,所以在Python 2中的整数和浮点数的查找速度差别不大。

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

下面的代码证明了Python 2.x中没有__contain__方法:

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)
in ()
1 print 'Python', python_version()
----> 2 xrange.__contains__

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

关于Python 2中xrange()与Python 3中range()之间的速度差异的一点说明:

有读者指出了Python 3中的range()和Python 2中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
%timeit test_while()
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
The proper way to raise an exception in 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中,函数形式和方法形式都可以使用,而在Python 3中,只能使用next()函数(试图调用.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中做的一个改动,在“What's New In 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()解析用户的输入

[回到目录]

幸运的是,Python 3改进了input()函数,这样该函数就会总是将用户的输入存储为str对象。在Python 2中,为了避免读取非字符串类型会发生的一些危险行为,不得不使用raw_input()代替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中返回的是可迭代对象,而不像在Python 2中返回列表。

由于通常对这些对象只遍历一次,所以这种方式会节省很多内存。然而,如果通过生成器来多次迭代这些对象,效率就不高了。

此时我们的确需要列表对象,可以通过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()
  • 字典的.key()方法
  • 字典的.value()方法
  • 字典的.item()方法

更多关于Python 2和Python 3的文章

[回到目录]

下面列出了其他一些可以进一步了解Python 2和Python 3的优秀文章,

//迁移到 Python 3

// 对Python 3的褒与贬

(0)

相关推荐

  • pyenv命令管理多个Python版本

    从接触Python以来,一直都是采用 virtualenv 和 virtualenvwrapper 来管理不同项目的依赖环境,通过 workon . mkvirtualenv 等命令进行虚拟环境切换,很是愉快. 然而,最近想让项目能兼容更多的Python版本,例如至少同时兼容 Python2.7 和 Python3.3+ ,就发现采用之前的方式行不通了. 最大的问题在于,在本地计算机同时安装 Python2.7 和 Python3 后,即使分别针对两个Python版本安装了 virtualenv

  • Python3.0与2.X版本的区别实例分析

    本文通过列举出一些常见的实例来分析Python3.0与2.X版本的区别,是作者经验的总结,对于Python程序设计人员来说有不错的参考价值.具体如下: 做为一个前端开发的码农,最近通过阅读最新版的<A byte of Python>并与老版本的<A byte of Python>做对比后,发现Python3.0在某些地方还是有些改变的.之后再查阅官方网站的文档,总结出一下区别: 1. 如果你下载的是最新版的Python,就会发现所有书中的Hello World例子将不再正确. Py

  • Windows下Python2与Python3两个版本共存的方法详解

    前言 一向用Python 3,最近研究微信公众号开发,各云平台只支持Python 2.7,想用其他版本需要自己搭建环境.而网上又搜不到Python 3开发微信公众号的资料.暂打算先使用Python 2.7,有空学习Docker后再迁移到Python 3. 安装Python 2.7后,本来在3.4下能正常使用的脚本无法运行.网上有的方法是把两个版本的主程序分别改名为python2和python3,人眼判断脚本,手输命令行执行脚本.像我这样喜欢双击.拖拽的懒人当然不会满足,找到了更智能的解决方案.

  • 编写同时兼容Python2.x与Python3.x版本的代码的几个示例

    编写兼容Python2.x与3.x代码 当我们正处于Python 2.x到Python 3.x的过渡期时,你可能想过是否可以在不修改任何代码的前提下能同时运行在Python 2和3中.这看起来还真是一个合理的诉求,但如何开始呢?哪些Python 2 代码在 3.x 解释器执行时容易出状况呢? print vs print() 如果你想的和我一样,你或许会说print语句,这是个很好的着手点,先简单展示一下,print在2.x中是一条语句,而在3.x中它是一个关键字或者是保留字.换句话说,因为这个

  • ubuntu下安装Python多版本的方法及注意事项

    今天一不小心又把ubuntu系统给完坏了,因为我把python3卸载了,然后就...好了,不废话了,接下来就说一下如何在ubuntu下管理python的多个版本.我这里使用的是一个叫pyenv的Python版本管理工具. 系统环境:ubuntu14.04LTS,系统默认的python版本为2.7,我这里想要再安装一个3.4.3版本. 再安装python之前,我们首先要安装这个管理工具pyenv: $ git clone git://github.com/yyuu/pyenv.git ~/.pye

  • Linux更新Python版本及修改python默认版本的方法

    linux下更新Python版本并修改默认版本,有需要的朋友可以参考下. 很多情况下拿到的服务器python版本很低,需要自己动手更改默认python版本 1.从官网下载python安装包(这个版本可以是任意版本3.3 2.7 2.6等等) wget http://python.org/ftp/python/2.7/Python-2.7.tar.bz2 2.解压并安装 tar -jxvf Python-2.7.tar.bz2 cd Python-3.3.0 ./configure make al

  • Python 2.7.x 和 3.x 版本的重要区别小结

    许多Python初学者都会问:我应该学习哪个版本的Python.对于这个问题,我的回答通常是"先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本.等学得差不多了,再来研究不同版本之间的差别". 但如果想要用Python开发一个新项目,那么该如何选择Python版本呢?我可以负责任的说,大部分Python库都同时支持Python 2.7.x和3.x版本的,所以不论选择哪个版本都是可以的.但为了在使用Python时避开某些版本中一些常见的陷阱,或需要移植

  • Python列表删除元素del、pop()和remove()的区别小结

    前言 在python列表的元素删除操作中, del, pop(), remove()很容易混淆, 下面对三个语句/方法作出解释 del语句 del语句可以删除任何位置处的列表元素, 若知道某元素在列表中的位置则可使用del语句. 例: >>> a = [3, 2, 2, 1] >>> del a[1] >>> a [3, 2, 1] pop()方法 pop()可删除任意位置的元素并将其返回, 只需在括号内指定要删除元素的索引即可, 当括号内为空时则删除

  • 理顺8个版本vue的区别(小结)

    一共8个版本的vue 术语 完整版:同时包含编译器和运行时的版本. 编译器:用来将模板字符串编译成为 JavaScript 渲染函数的代码. 运行时:用来创建 Vue 实例.渲染并处理虚拟 DOM 等的代码.基本上就是除去编译器的其它一切. UMD:UMD 版本可以通过 <script> 标签直接用在浏览器中.jsDelivr CDN 的 https://cdn.jsdelivr.net/npm/vue 默认文件就是运行时 + 编译器的 UMD 版本 (vue.js). CommonJS:Co

  • Python使用Pyqt5实现简易浏览器(最新版本测试过)

    准备环境 首先我们需要的是我们的开发环境,我使用的是python 3.8.2和pyqt 5.14.2,因为有强迫症,所以喜欢使用最新版的 安装QtWebEngineWidgets 这是新版使用的web浏览器引擎,更加的贴近谷歌浏览器,好像是需要单独安装,我就是这样的 pip3 install QtWebEngineWidgets 多tab页面 做这个的时候遇到好多坑,比如在多个tab里面打开页面,要使用这个QTabWidget,这个不用我们再去下载了,已经集成了 页面链接点击无反应 这个搞了我半

  • Python2.x与3​​.x版本有哪些区别

    Python的3​​.0版本,常被称为Python 3000,或简称Py3k.相对于Python的早期版本,这是一个较大的升级. 为了不带入过多的累赘,Python 3.0在设计的时候没有考虑向下相容. 许多针对早期Python版本设计的程式都无法在Python 3.0上正常执行. 为了照顾现有程式,Python 2.6作为一个过渡版本,基本使用了Python 2.x的语法和库,同时考虑了向Python 3.0的迁移,允许使用部分Python 3.0的语法与函数. 新的Python程式建议使用P

  • 对Python的交互模式和直接运行.py文件的区别详解

    看到类似C:\>是在Windows提供的命令行模式,看到>>>是在Python交互式环境下. 在命令行模式下,可以执行python进入Python交互式环境,也可以执行python hello.py运行一个.py文件,但是在Python交互 式环境下,只能输入Python代码执行. Python的交互模式和直接运行.py文件有什么区别呢? 直接输入python进入交互模式,相当于启动了Python解释器,但是等待你一行一行地输入源代码,每输入一行就执行一行. 直接运行.py文件相当

  • Python定义一个跨越多行的字符串的多种方法小结

    方法一: >>> str1 = '''Le vent se lève, il faut tenter de vivre. 起风了,唯有努力生存. (纵有疾风起,人生不言弃.)''' >>> str1 'Le vent se lève, il faut tenter de vivre. \n起风了,唯有努力生存.\n(纵有疾风起,人生不言弃.)' 编辑的时候,引号挺对的,但是不知道为什么发布的时候,第一行的引号总是多了一些,其实应该是下面这样的: 不过感觉这种方法不够纯粹

  • 浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

    Python2的字符串有两种:str和Unicode,Python3的字符串也有两种:str和Bytes.Python2的str相当于Python3的Bytes,而Unicode相当于Python3的Bytes. Python2里面的str和Unicode是可以混用的,在都是英文字母的时候str和unicode没有区别. 而Python3严格区分文本(str)和二进制数据(Bytes),文本总是Unicode,用str类型,二进制数据则用Bytes类型表示,这样严格的限制也让我们对如何使用它们有

  • 判断python对象是否可调用的三种方式及其区别详解

    查找资料,基本上判断python对象是否为可调用的函数,有三种方法 使用内置的callable函数 callable(func) 用于检查对象是否可调用,返回True也可能调用失败,但是返回False一定不可调用. 官方文档:https://docs.python.org/3/library/functions.html?highlight=callable#callable 判断对象类型是否是FunctionType type(func) is FunctionType # 或者 isinst

  • 用python介绍4种常用的单链表翻转的方法小结

    如何把一个单链表进行反转? 方法1:将单链表储存为数组,然后按照数组的索引逆序进行反转. 方法2:使用3个指针遍历单链表,逐个链接点进行反转. 方法3:从第2个节点到第N个节点,依次逐节点插入到第1个节点(head节点)之后,最后将第一个节点挪到新表的表尾. 方法4: 递归(相信我们都熟悉的一点是,对于树的大部分问题,基本可以考虑用递归来解决.但是我们不太熟悉的一点是,对于单链表的一些问题,也可以使用递归.可以认为单链表是一颗永远只有左(右)子树的树,因此可以考虑用递归来解决.或者说,因为单链表

随机推荐