变量其实就是用来存储数据的内存空间,可以在变量中存储各种类型的数据,比如:整数,浮点数(小数),字符串等。在Python中,设置变量时,并不需要去明确的声明它所存储的数据类型。当我们给某个变量赋值时,解释器会在内部自动将其设定为对应的类型...

    页面导航:
英文教程的下载地址:

    本篇文章是根据英文教程《Python Tutorial》来写的学习笔记。该英文教程的下载地址如下:

    百度盘地址:http://pan.baidu.com/s/1c0eXSQG

    DropBox地址:点此进入DropBox链接

    Google Drive:点此进入Google Drive链接

    这是学习笔记,不是翻译,因此,有些内容,作者会略过。以下记录主要是根据英文教程的第四章来写的。(文章中的部分链接,可能需要通过代理访问!)

变量的基本概念:

    变量其实就是用来存储数据的内存空间,可以在变量中存储各种类型的数据,比如:整数,浮点数(小数),字符串等。

    在Python中,设置变量时,并不需要去明确的声明它所存储的数据类型。当我们给某个变量赋值时,解释器会在内部自动将其设定为对应的类型,例如,下面的例子:

counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name


    上面的等号(=)就是赋值运算符,在赋值运算符的左侧是变量名,右侧则是要设置的数据,上面依次将100,1000.0及"John"三个数据设置到counter,miles及name变量中,我们可以将代码保存到testval.py文件里,在命令行下的运行结果如下:

[email protected]:~/Pytest/ch4$ python testval.py 
100
1000.0
John
[email protected]:~/Pytest/ch4$ 


    此外,我们还可以在一条语句中,同时为多个变量赋予相同的值:

name = miles = counter = 100 # Multiple assignment
print counter
print miles
print name


    运行结果如下:

[email protected]:~/Pytest/ch4$ python testval.py 
100
100
100
[email protected]:~/Pytest/ch4$ 


    上面是多个变量赋予相同的值的例子,其实,还可以在同一条语句中,为不同的变量赋予不同的值:

counter, miles, name = 100, 1000.0, "John" # Multiple assignment
print counter
print miles
print name


    运行结果如下(上面会将右侧的三个值,依次赋值给左侧的三个变量):

[email protected]:~/Pytest/ch4$ python testval.py 
100
1000.0
John
[email protected]:~/Pytest/ch4$ 


    在Python中,有以下几种标准的数据类型:
  • Numbers (数字类型)
  • String (字符串类型)
  • List (列表类型)
  • Tuple (元组类型)
  • Dictionary (词典类型)
  • set与frozenset类型
    下面就对这些数据类型,依次进行介绍。

数字类型:

    Python支持以下四种不同的数字类型:
  • int (signed integers) 有符号的整数类型
  • long 长整数类型
  • float 浮点数
  • complex 复数
    int与long都是整数类型,它们的区别在于:int有一个明确的最大值与最小值,而long则没有明确的范围限制,long的范围仅受限于程序可以访问的内存空间的大小,当int类型的变量的值超出范围时,会自动切换到long类型。此外,在python 3.x的版本中,只存在long长整数类型,而不存在int这种受限的整数类型了。

    我们可以通过 sys.maxint 或者 sys.maxsize 来查看int类型的最大值:

import sys
print sys.maxsize
print sys.maxint


    可以将上面的代码保存到testval.py文件中,运行结果如下:

[email protected]:~/Pytest/ch4$ python testval.py 
2147483647
2147483647
[email protected]:~/Pytest/ch4$ 


    在python 3.x的版本中,sys.maxint已经被移除了。当然,在3.x的版本中,还可以使用sys.maxsize来查看。在32位系统里,int的最大值是2^31-1(即2的31次方减1),在64位系统中,最大值则是2^63-1(即2的63次方减1)。

    我们可以使用long来进行大整数运算:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> test = 51924361L
>>> print type(test)
<type 'long'>
>>> test2 = test * 65535
>>> print type(test2)
<type 'long'>
>>> print test2
3402862998135
>>> quit()
[email protected]:~/Pytest/ch4$ 


    通过在数字后面加上L字符,就表示该数字是long长整数类型(如上面的51924361L),可以用type函数来检测变量的类型,例如,上面的type(test)函数所返回的字符串信息<type 'long'>就说明test变量存储的是long类型的整数,test * 65535得到的结果远超出int类型可以表示的范围,因此,test2就会自动以long类型来保存结果。

    float浮点数也是有范围的,其范围与C语言里的double(双精度浮点数)的范围类似,在python里,可以通过sys.float_info来查看其范围:


[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30)
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
>>> quit()
[email protected]:~/Pytest/ch4$

    在使用sys之前,需要先通过import sys来导入该模块(模块的概念在以后的章节中会介绍),上面输出显示的maxmin分别为float浮点数的最大值与最小值。

    有关float浮点数在计算机里的概念及原理,可以参考汇编语言栏目中的"汇编数据处理 (三) 浮点数"的文章。

    在python里,要使用float的话,既可以使用常规的小数格式,也可以使用科学技术法的格式:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> test = 3.14
>>> print test
3.14
>>> test = 3.14e8  
>>> print test
314000000.0
>>> test = 3.14E12
>>> print test
3.14e+12
>>> test = 3.14e+12
>>> print test
3.14e+12
>>> test = 3.14e-12
>>> print test
3.14e-12
>>> quit()
[email protected]:~/Pytest/ch4$ 


    在Python中,还可以表示复数,有关复数的概念,可以参考 复数-维基百科 该链接对应的文章。

    在维基百科中,给出了复数相关的加减乘除的法则,我们可以在Python里对这些运算法则进行测试:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = (1+2j)
>>> b = (3+4j)
>>> print a+b
(4+6j)
>>> print a-b
(-2-2j)
>>> print a*b
(-5+10j)
>>> print a/b
(0.44+0.08j)
>>> quit()
[email protected]:~/Pytest/ch4$ 


    不过,这里需要注意的是:在python里,是使用 j 来表示虚数单位的(电子工程领域一般也都是用j),而不是数学公式里的 i 。

字符串类型:

    在上一章中,我们介绍过字符串的定义方法,即:可以通过单引号、双引号或三重引号来定义一个字符串。在将字符串设置到变量中后,还可以通过中括号来访问变量里的单个字符或者其中的子字符串,例如下面的例子:

#teststr.py

str = 'Hello-World!'

print str # Prints complete string
print str[0] # Prints first character of the string
print str[-1] # Prints last character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str[:-2]
print str[:] # Prints complete string
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string


    上面代码里,通过中括号和索引值,可以访问字符串里的单个字符,索引值为0表示第一个字符,为1则表示第二个字符,以此类推。另外,索引值为-1表示最后一个字符,为-2则表示倒数第二个字符,以此类推。因此,上面的str[0]就可以访问到第一个'H'字符,str[-1]则访问的是最后一个'!'字符。

    除了可以访问单个字符外,还可以通过冒号来访问其中的子字符串。冒号左侧的数值为子串的起始索引,右侧的数值为子串的结束索引(但最终提取的子串里不会包含结束索引在内),所以,str[2:5]表示将索引值为2到索引值为4的子字符串给提取出来(但不包括索引值为5的字符),如果冒号左侧的数值留空的话,则表示起始索引值为0,如果右侧的数值留空的话,则表示从起始索引到最后一个字符都提取出来,如果左右两侧全留空的话,那么就是将整个字符串提取出来。

    还可以通过乘法运算符,将字符串以拷贝的形式进行扩展,例如上面的str * 2,得到的结果就会是"Hello-World!Hello-World!",我们还可以使用加号来连接两个字符串,例如上面的str + "TEST",得到的结果就会是"Hello-World!TEST",我们将上面的代码保存到teststr.py文件里,运行结果如下:

[email protected]:~/Pytest/ch4$ python teststr.py
Hello-World!
H
!
llo
llo-World!
Hello-Worl
Hello-World!
Hello-World!Hello-World!
Hello-World!TEST
[email protected]:~/Pytest/ch4$ 


list列表类型:

    在Python中,list(列表)的概念类似于C语言里的数组,只不过,列表里存储的元素可以是不同的数据类型,而且,列表的尺寸大小可以动态的改变。下面就是一个列表的例子:

#testlist.py

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']

print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists


    上面的代码是通过中括号来创建的列表,列表里的各个元素通过逗号来隔开。我们可以像访问字符串里的单个字符那样,来访问列表里的某个成员,还可以通过冒号来提取出其中的子列表。其访问方式与字符串的访问方式是一致的。此外,同样可以利用乘法运算符对列表进行拷贝扩展,以及通过加法运算符来连接两个列表。

    我们将上面的代码保存到testlist.py文件里,运行结果如下:

[email protected]:~/Pytest/ch4$ python testlist.py 
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
[email protected]:~/Pytest/ch4$ 


tuple元组类型:

    tuple元组类似于list列表,也是用于存储多个元素的集合,只不过tuple元组是只读的,它里面的成员是不能被修改的,元组的尺寸大小也不可以改变。创建元组需要使用小括号,如下所示:

#test_tuple.py

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

tinytuple = (123, 'john')

print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists


    可以看到,与之前testlist.py的例子相比,除了创建元组时,是用的小括号外,其他的代码都没什么不同,元组的成员访问方式,与列表的访问方式是一致的。上面代码的运行结果如下:

[email protected]:~/Pytest/ch4$ python test_tuple.py 
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
[email protected]:~/Pytest/ch4$ 


    我们可以通过下面的例子,来看出tuple元组与list列表的区别:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> tuple = (123, 456)
>>> list = [123, 456]
>>> tuple[0] = 1000
Traceback (most recent call last):
  File "<stdin>", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> list[0] = 1000
>>> print list
[1000, 456]
>>> list.append(789)
>>> print list
[1000, 456, 789]
>>> tuple.append(789)
Traceback (most recent call last):
  File "<stdin>", line 1, in 
AttributeError: 'tuple' object has no attribute 'append'
>>> quit()
[email protected]:~/Pytest/ch4$ 


    上面在python的交互式界面里,将tuple变量设置为了元组,将list变量设置为了列表,当tuple[0] = 1000语句执行时,抛出了错误信息,说明元组里的成员是只读的,不可以被修改,而list[0] = 1000则可以执行,即列表里的成员是可以被修改的。

    此外,list可以通过append方法,在列表后面添加新的成员,即列表的尺寸大小是可以动态改变的,而tuple元组则不存在类似的方法,即元组的尺寸大小是不可以被改变的。

    元组的这种只读,不可变的性质,使得元组可以成为后面要介绍的dictionary(词典)里的key,还可以成为后面要介绍的set集合里的成员。

dictionary词典类型:

    Python里的词典,类似于PHP语言中的数组,是包含key-value(名值对)的集合,可以通过大括号来创建词典,如下所示:

#test_dict.py

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values


    上面代码的运行结果如下:

[email protected]:~/Pytest/ch4$ python test_dict.py 
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
[email protected]:~/Pytest/ch4$ 


    当大括号里面为空时,就表示创建一个空的词典,如果是非空的词典,则大括号里的每个key-value(名值对)需要用冒号来隔开,冒号左侧为key(名),冒号右侧为value(值),如上面的'name':'john' 。每个名值对之间需要通过逗号来隔开,在访问词典里的成员时,是通过key来访问的,例如上面的dict['one'],dict[2],或者是tinydict['name']的形式,这里的'one',2及'name'都是key 。

    key-value(名值对)里的value可以是任意的数据类型,但是key对应的数据,则必须是hashable(可计算出哈希值)的数据类型,我们可以通过hash函数来测试哈希值:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hash(123)
123
>>> hash('name')
15034981
>>> hash((3,4))
1699342716
>>> hash([3,4])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
>>> dict = {(3,4):'john'}
>>> print dict[(3,4)]
john
>>> dict = {[3,4]:'john'}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
>>> quit()
[email protected]:~/Pytest/ch4$ 


    从上面的交互式输出结果中,可以看到,数字123,字符串'name',以及元组(3,4)都是可以计算出哈希值来的,但是[3,4]这个list列表类型则不能计算出对应的哈希值来,在python里,通常只有不可变的数据类型,才可以计算出哈希值,像数字、字符串、元组等。如果是可变的数据类型,如列表类型等,则不能计算出对应的哈希值。

    由于词典类型的数据,在python内部,保存的其实是key的哈希值,当需要访问词典里的某个key时,会先计算出该key的哈希值,然后再通过哈希值来找到对应的value ,接着才可以对找到的value进行读写操作。因此,如果某个数据不能计算出哈希值来的话,就不能将该数据作为key 。

    如果在创建词典时,大括号中,两个key对应的哈希值是一样的话,那么前一个key的value会被后一个key的value给覆盖掉,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hash(123)
123
>>> hash(123.0)
123
>>> dict = {123:'hello',123.0:'end'} 
>>> print dict
{123: 'end'}
>>> print dict.keys()
[123]
>>> print dict.values()
['end']
[email protected]:~/Pytest/ch4$


    可以看到,123与123.0的哈希值都是123,因此,后面的123.0的值'end'会将之前123的值'hello'给覆盖掉,这样,dict词典里就只会存在一个哈希值为123的key-value(名值对)了,通过哈希值,词典就可以确保其包含的key-value(名值对)的唯一性,即不会有重复的key-value出现,也不会有相同哈希值的key出现。

set与frozenset类型:

    大括号除了可以用来创建词典外,还可以用来创建set数据类型,set也是包含多个数据元素的集合,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> set = {123, 'john'}    
>>> print set
set([123, 'john'])
>>> quit()
[email protected]:~/Pytest/ch4$ 


    从上面输出可以看到,当大括号里面包含的不是key-value(名值对)时,则创建的就会是set,set是通过哈希值来存储数据元素的,因此,它里面只能包含hashable(可计算出哈希值)的数据类型,如果是列表之类的不能计算哈希值的数据,则无法添加到set中,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> set = {123, [3,4]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
>>> set = {123, (3,4)}
>>> print set
set([123, (3, 4)])
>>> quit()
[email protected]:~/Pytest/ch4$ 


    上面的输出显示,由于[3,4]是列表,不能计算其哈希值,因此,它不能作为set的数据元素,而(3,4)是元组,可以计算出哈希值来,因此,(3,4)可以作为set的数据元素。

    此外,由于set是使用哈希值来存储数据元素的,因此,它里面的数据元素都是唯一的,在set里不会有相同哈希值的数据存在,从而确保了set里所包含的数据的唯一性,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> set = {123, 'john', 123, 123.0, 'john'}
>>> print set
set([123.0, 'john'])
>>> quit()
[email protected]:~/Pytest/ch4$ 


    由于123,123.0具有相同的哈希值,因此,它们会被存储在同一个空间里,并且,在该空间中,后面的值会将前面的值给覆盖掉,因此,set里最后就只有一个123.0,同理,也只会保留一个'john' 。这样通过哈希值,就把重复的数据给剔除掉了。

    由于set是利用哈希值来存储数据的,所以,set的数据元素都是无序的,不能像列表那样,通过索引来访问数据,只能通过以后要介绍的迭代方法,或者将set转换成list(列表),才能访问到其中的指定的数据。

    list(列表)与set是可以相互转换的,当我们需要将列表里的数据进行唯一性处理(即去掉重复的数据)时,就可以先将其转换为set,最后再将set转换为列表,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list = [345, 'name', 'hello', 'name', 345, 'zengl', 'zengl']
>>> print list
[345, 'name', 'hello', 'name', 345, 'zengl', 'zengl']
>>> set = __builtins__.set(list)
>>> print set
set([345, 'zengl', 'name', 'hello'])
>>> list = __builtins__.list(set)
>>> print list
[345, 'zengl', 'name', 'hello']
>>> print list[0]
345
>>> print list[1]
zengl
>>> quit()
[email protected]:~/Pytest/ch4$ 


    上面先通过内建模块里的set函数,将list列表转为set类型,转换后,在set变量里,就不存在重复的数据了,最后就可以通过list函数,将set再转换为list(列表)类型,这样列表中的数据就是唯一的了,接着,就可以通过索引来访问这些列表数据了。由于在上面的python代码中,使用到了list与set作为变量名,因此为了防止与list和set函数名相冲突,就在set与list函数之前加了一个__builtins__的内建模块名,如果python代码里没有与函数冲突的变量名的话,可以去掉__builtins__的模块名,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [345, 'name', 'hello', 'name', 345, 'zengl', 'zengl']    
>>> print l
[345, 'name', 'hello', 'name', 345, 'zengl', 'zengl']
>>> s = set(l)
>>> print s    
set([345, 'zengl', 'name', 'hello'])
>>> l = list(s)
>>> print l
[345, 'zengl', 'name', 'hello']
>>> print l[0]
345
>>> print l[1]
zengl
>>> quit()
[email protected]:~/Pytest/ch4$ 


    除了set类型外,还有一个frozenset数据类型,frozenset与set的区别在于:frozenset是只读的,不可变的(可以计算出哈希值),set则是可变的(可以通过add之类的方法来添加数据),不能计算哈希值,如下所示:

[email protected]:~/Pytest/ch4$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = {123, 'john'}
>>> f = frozenset(s)
>>> hash(f)
1398992158
>>> hash(s)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'set'
>>> quit()
[email protected]:~/Pytest/ch4$ 


    上面通过frozenset函数就可以将set转换为frozenset类型,该类型的数据可以通过hash函数得出其哈希值,而set类型的数据则不能计算出其哈希值来。

数据类型转换:

    Python中的各个数据类型之间是可以相互转换的,例如,上面提到的list(列表)与set,以及frozenset与set,它们之间都可以通过特定的函数来进行转换,至于其他的数据类型的转换,则可以参考下表中的函数(这些都是内建的模块函数):

Function
函数
Description
描述
int(x [,base]) 将参数x转换为int整数类型,如果指定了base参数(base用于指明x是10进制,8进制还是16进制数),则x必须是一个字符串
long(x [,base]) 将参数x转换为long类型的整数,如果指定了base参数,则x必须是一个字符串
float(x) 将参数x转换为浮点数
complex(real [,imag]) 创建一个以real为实部,imag为虚部的复数
str(x) 将参数x转换为字符串
repr(x) 将参数x转换为解释器可执行的字符串格式
eval(str) 将str字符串当作表达式来进行计算,并将计算的结果返回
tuple(s) 将参数s转换为tuple元组
list(s) 将参数s转换为list列表类型
set(s) 将参数s转换为set类型
dict(d) 通过参数d来创建并返回一个词典
frozenset(s) 将参数s转换为frozenset类型
chr(x) 根据ASCII码,将整数x转换为一个字符
unichr(x) 将整数x转换为一个unicode字符
ord(x) 返回字符x所对应的ASCII码值
hex(x) 将整数x转换为16进制格式的字符串
oct(x) 将整数x转换为8进制格式的字符串

    上表中的这些函数都好理解,这里只对个别函数进行介绍,从上表中可以看到,str(x)与repr(x)都是用于将参数转换为字符串的函数,它们的区别在于:str(x)函数转换出来的是human-readable(人类可读)的字符串,而repr(x)转换出来的是read by the interpreter即可被解释器解析的表达式格式的字符串,如果repr的参数x无法转换为一个有效的表达式格式的字符串的话,repr函数还会抛出语法错误。这两个函数的区别,可以参考下面的例子:

[email protected]:~$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'hello'     
>>> print str(s)
hello
>>> print repr(s)
'hello'
>>> exec('print ' + repr(s))
hello
>>> exec('print ' + str(s))
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'hello' is not defined
>>> quit()
[email protected]:~$ 


    上面输出显示,str(s)返回的就是原字符串hello,而repr(s)返回的字符串里还会在hello两边加上单引号(有的python版本可能会加上双引号),这样带引号的'hello'就可以被解释器解析为字符串。

    上面用到了exec函数,该函数的作用是将字符串当作python语句来执行,这样exec('print ' + repr(s))函数里的参数就会是:print 'hello',这是一个有效的语句,因此,exec函数就可以正确执行该语句。而exec('print ' + str(s))函数里的参数则是:print hello,该语句里的hello因为没有被引号包含起来,因此hello会被当作变量标识符,而hello是一个无效的变量(之前没有语句对其进行过赋值之类的初始化操作),所以,exec执行该语句时,就会抛出语法错误了。

    在前面的函数表格里,有一个eval函数,该函数的作用是将字符串当作表达式来进行计算,并返回计算的结果,它与exec函数的区别在于:eval是一个函数,只能计算表达式,不能执行语句,而exec则是一个python关键字,它可以将字符串当作语句来执行,如下所示:

[email protected]:~$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval('1+2')
3
>>> eval('a = 1+2')
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
    a = 1+2
      ^
SyntaxError: invalid syntax
>>> eval('print "hello"')
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
    print "hello"
        ^
SyntaxError: invalid syntax
>>> exec('a = 1+2')
>>> exec('print "hello"')
hello
>>> exec 'a = 1+2' 
>>> exec 'print a'
3
>>> quit()
[email protected]:~$ 


    从上面的输出可以看到,eval只能计算'1+2'之类的表达式,它还会返回计算的结果,但是像'a = 1+2'之类的赋值语句,以及'print "hello"'之类的打印语句则无法执行,而exec则可以像解释器一样正确的执行这些赋值打印之类的python语句。另外,虽然exec可以执行语句,但是它的执行速度比eval函数要慢的多,因为它比eval要做更多的解析工作。

    有关dict函数的用法,可以参考 https://docs.python.org/2/library/stdtypes.html?highlight=dict#dict 该链接,在该链接里,给出了dict函数创建词典的几种方式:

[email protected]:~$ python
Python 2.7.8 (default, Nov 26 2014, 11:28:30) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict([('two', 2), ('one', 1), ('three', 3)])
>>> d = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d
True
>>> print a
{'three': 3, 'two': 2, 'one': 1}
>>> print b
{'three': 3, 'two': 2, 'one': 1}
>>> print c
{'three': 3, 'two': 2, 'one': 1}
>>> print d
{'one': 1, 'three': 3, 'two': 2}
>>> quit()
[email protected]:~$ 


    上面显示了创建词典的几种方式,可以通过大括号来创建,也可以通过dict函数来创建,使用dict函数创建时,参数可以使用列表加元组的方式,每个元组的第一项作为key,第二项则作为value。此外,由于词典的key是以哈希值的形式进行存储的,因此,词典里的key-value(名值对)都是无序的,在print显示时,哪个key-value排前面,哪个排后面都不影响结果(即上面a,b,c,d比较时都会是相等的)。

    其他的函数则请参考python的官方手册。

    限于篇幅,本章就到这里。

    OK,休息,休息一下 o(∩_∩)o~~
上下篇

下一篇: Python基本的操作运算符

上一篇: Python的基本语法

相关文章

Python的流程控制语句

Python的time模块

Python基本的I/O操作 (四)

Python随机数函数

Python相关的数学运算函数

Python三角函数