python3.3官方手册学习(第一部分)

 
 

 

1.    开胃菜

        注意:    官网下载的安装文件自带命令行执行窗口和 IDLE 

2.    使用python解释器

        本章准备知识:    

                1.    设置安装路径

                        linux:    export path=%path%;/usr/local/bin        ----默认python会安装在这个目录下

                        win:    set path=%path%;C:\python33        ----python在windows下的默认安装环境

                2.    退出 IDLE的方式

                        ctrl+d或者quit()

                3.    检查IDLE是否支持命令行编辑

                        ctrl+p        ----如果主窗口显示^p说明不支持;弹出一个窗口则说明支持

                4.    启用python解释器的两种方式

                        1.    在shell中执行*.py的脚本

                        2.    python -c .[command] [arg]        ----在 命令行 执行 Python 语句或模块,一般建议将 命令 用单引号包裹起来

        2.1.    调用 python 解释器

                2.1.1.    参数传递

                       情况一:    调用解释器式没有给定脚本和参数,直接打开解释器旧式这种情况

 

>>> import sys>>> sys.argv[0]' '          ----空字符串

 

                        情况二:    脚本名指定为 '-' (表示标准输入)时

$ python -      

                        情况三:    使用 -c 指令 时, sys.argv[0] 被设定为 '-c' 。

                        情况四:    使用 -m 模块 参数时, sys.agv[0] 被设定为指定模块的全名

                       注:情况三、四 下参数不会被 Python 解释器的选项处理机制所截获,而是留在 sys.argv 中,供脚本命令操作

                2.1.2.    交互模式

 

$ python3.3        ----进入交互模式 Python 3.3 (py3k, Sep 12 2007, 12:21:02) [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2Type "help", "copyright", "credits" or "license" for more information. >>> the_world_is_flat = 1        --------主提示符通常标识为三个大于号 (>>>) >>> if the_world_is_flat:  ...     print("Be careful not to fall off!")        --------继续的部分被称为 从属提示符  ...  Be careful not to fall off!                 

 

        2.2.    解释器及其环境

                2.2.1.    错误处理

                        1.    交互模式下,会打印错误信息并返回到主提示符,比如输入中断符会抛出KeyboardInterrupt异常

                                中断符:    【ctrl+c】or 【del】

                        2.    执行文件的模式下会打印栈跟踪器后以非零状态退出

                        3.    可以用try语句中的except拉哎控制

                2.2.2.    执行Python脚本

                        1.    UNIX

                                脚本首行:    #! /usr/bin/env python3.3

                                权限:    $ chmod +x myscript.py

                        2.    WIN

                                脚本首行:    #! /usr/bin/env python3.3(不需要,即使有也会被当作一般注释忽略)

                                权限:    不需要关心

                                双击:    python安装程序通过注册表将.py关联,.pyw也做了关联,但不会显示cmd窗口

                2.2.3.    源程序编码

                        1.    python源文件默认是UTF-8编码

                        2.    自定义文件的编码

 

 #! /usr/bin/env python3.3 # -*- coding: encoding -*-        ----这个特殊的编码注释必须在文件中的 第一或第二 行定义

 

                2.2.4.    交互执行文件

                        1.    每次解释器启动时执行一些命令

                                设定一个名为 PYTHONSTARTUP的环境变量来指定这个文件。

                        2.    如果你想要在当前目录中执行附加的启动文件

                                可以在全局启动文件中加入类似以下的代码:

 

 if os.path.isfile('.pythonrc.py'):       execfile('.pythonrc.py')import os

 

                        3.    如果你想要在某个脚本中使用启动文件

                                必须要在脚本中写入这样的语句:

 

filename = os.environ.get('PYTHONSTARTUP')if filename and os.path.isfile(filename): exec(open(filename).read())

 

                2.2.5.    本地化模块

                        1.    usercustomize

 >>> import site>>> site.getusersitepackages()        ----site-packages 目录'/home/neo/.local/lib/python3.3/site-packages'                       

                               现在你可以在 site-packages 的目录下创建 usercustomize.py 文件,内容就悉听尊便了。 这个文件将会影响 python 的每次调用,除非启动的时候加入 -s 选项禁止自动导入。

                        2.    sitecustomize (和1类似)

                                但是是由电脑的管理账户创建以及在 usercustomize 之前导入。 具体可以参见 site 。

3.    Python简介

        3.1.    将Python当作计算器

                3.1.1.    数字

                            1.    取整除法:    //

                            2.    连续赋值:    x = y = z = 1   

                            3.    变量使用前需要“定义”(即赋值)

                            4.    整数于浮点数混合计算是自动转化为浮点数

                            5.    支持复数

 

 >>> z = 2+1j / 2+1J/cpmplex(1,2)>>> z.real  2>>> z.imag 1>>> abs(z)>>>2.23606797749979

 

                            6.    数据类型转换函数

                                    int()/float()/long()        ----不能用于复数

                            7.    监护模式下python会将最后一个变量的值赋给_

               3.1.2.    字符串

                        1.    即可以用单引号也可以用双引号标识

                        2.    " "中只有 '不需要转译,' '中的 "不需要转译。

                        3.    print()函数可以生成 更好的输出4    

                        4.    使用 \ 放在字符串尾来连接不同行的字符串

                        5.    """或''':    三引号中的所有字串都将保持原样,转译字符的转移功能都会失效

                        6.    字符串可以用“+”连接,可以由"*"重复

                        7.    相邻两个字符串文本自动连接在一起(只针对字符串文本)

                        8.    没有类似 c 的 char 类型

                        9.    字符串可以通过索引的方式截取,比如 

 

>>> word = "hello" >>> word[0:1]        ----相当于word[0] 或word(:1)'h'

 

                        10.    python字符串不可变。想字符串某一个索引赋值会引发错误

                        11.    切片操作不变的一点s[:i]+s[i:] = s

                        12.    能够优雅地处理没有意义的索引方式

                                a.    索引大于字符串实际长度时将被实际长度替代

                                b.    上边界大于下边界这种情况将返回""

                                c.    索引也可以是负数,将导致从右边开始算,-1代边倒数第一个字符 

                                        +---+---+---+---+---+

                                         | H |  e |  l | p | A |

                                        +---+---+---+---+---+

                                        0    1     2   3   4   5

                                       -5   -4    -3  -2  -1

                         13.    内置函数 len() 返回字符串的长度

                3.1.3.    关于Unicode

                        1.    通过对应unicode的序列号插入特殊字符

 

>>> 'Hello\u0020world!'        ----'\u0020'是空格的unicode序列号>>> 'Hello world!'

 

                        2.    编码小于256的unicode和latin-1编码表示的字符是一致的

                        3.    通过已知字符串创建unicode编码

 

 >>> "abcس ".encode('utf-8') b'abc\xd8\xb3 '

 

                3.1.4.    列表

                        1.    列表的元素不必是同一种类

                        2.    列表支持像字符串那样索引/切片/连接

                        3.    切片操作返回的是对原列表浅拷贝的副本(意味着只是拷贝了指向同意空间的一些引用)

                        4.    列表允许修改元素

                        5.    列表可以通过赋值增大或通过清空某些元素减小

                        6.    列表可以使用内置函数 len() 计算元素的个数

                        7.    可以通过函数append()在列表末尾添加内容

        3.2.    编程的第一步

                1.    python支持多重赋值:    a, b = b, a+b    ----先从左到右计算右边的表达式然后才赋值 

                2.    任何非零整数/非空字符串/非空列表表示 true, 0/空字符串/空列表表示false

                3.    使用缩进组织代码,同意语句体需要同样数量空白的缩进

                4.    print():    通过逗号连接打印的内容,end=','结尾可以禁止换行

4.    深入Python流程控制

        4.1.    if语句

                1.    一个实例:

 

 >>> x = int(input('Pease input an integer:'))Please input an integer:>>> if x == 0:. . .      print('zero'). . .  elif x < 0:                ----else ifx < 0:. . .     print('below zero'). . .  else:. . .      print('above zero')

 

        4.2.    for语句

                1.    一个实例

 

>>> a = ['a', 'ab', 'abc']>>> for x in a: . . .      if len(x) > 2:  . . .          a.insert(0, x). . .  >>> a['abc', 'a', 'ab', 'abc']

 

                2.    range()

 

>>> a = ['how ', 'do ', 'you ', 'know', '?']>>> for i in range(len(a)) . . .      print(i, a[i]) . . . 0 how 1 do 2 you 3 know 4 ?

 

                3.    可迭代对象

                        1.    range()

 

>>> print(range(10)) range(0, 10)                ----range()函数并不会在内存中构造一个列表,只会构造一个能够按照期望返回序列的对象

 

                        2.    更多

                4.    迭代器:    可以从可迭代对象迭代出序列

                        1.    for循环

                        2.    list():    

 

>>> list(range(2)) [0,1, 2]

 

                        3.    更多

                5.    python的for或while循环可以有一个else语句(jave, js, c/c++等都不具有)

 

 ...     for x in range(2, n): ...         if n % x == 0: ...             print(n, 'equals', x, '*', n//x)...             break ...     else:                ----else语句在for迭代完毕或while条件判断false时执行,如果迭代中发生break则跳过else语句...         # loop fell through without finding a factor...         print(n, 'is a prime number')...                       

 

        4.3.    break和continue语句,预计循环的else子句

                1.    break:    和c类似,略

                2.    continue:    和c类似,略

        4.4.    pass语句

                1.    pass 语句什么也不做。它用于那些语法上必须要有什么语句,但程序什么也不做的场合

                2.    实例

 

>>> while True:...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)...>>> class MyEmptyClass: ...     pass ...>>> def initlog(*args): ...     pass   # Remember to implement this! ...
 

 

        4.5.    定义函数

                1.    一个实例

>>> def fib(n):    # write Fibonacci series up to n        ----可以将fib赋给其他变量 ...         """Print a Fibonacci series up to n."""        ----可选的字符串文本(docstring),通过一些工具可以生成在线的文档...         a, b = 0, 1        ----函数内的变量赋值都是将值赋给函数被调用时创建的局部符号表...         resule = []        ----一个链表对象...         while a < n:...             result.append(a)             ...             a, b = b, a+b        ----引用变量的查找顺序:(假设引用发生在函数内部)1.函数内部的局部变量表->2.包含函数名的局部变量表->3.全局符号表->4.内置符号表,全局变量不能在函数中直接赋值,除非用global语句...         return result ...>>> # Now call the function we just defined: ... x = 2000 >>> fib(x)        ----函数引用的实际参数在函数调用时引入局部符号表,通过传值调用(复制)方式,只不过这里的值值得是引用地址,类似于java[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]         

        4.6.    深入python函数定义

                4.6.1.    默认参数值

                        1.    一个实例:    4个参数,3个给定默认值,调用时至少给一个实参,实参按顺序赋给形参

 

                                def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):                                            while True:                                        ok = input(prompt)                                        if ok in ('y', 'ye', 'yes'):        ----in:    测定序列中是否包含某个确定的值                                            return True                                        if ok in ('n', 'no', 'nop', 'nope'):                                            return False                                        retries = retries - 1                                        if retries < 0:                                            raise IOError('refusenik user')                                        print(complaint)

 

                        2.    默认值只会在第一次调用时赋值一次,

                4.6.2.    关键字参数

                        1.    一个实例

                            函数原型:

 

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):     print("-- This parrot wouldn't", action, end=' ')     print("if you put", voltage, "volts through it.")     print("-- Lovely plumage, the", type)     print("-- It's", state, "!")

 

用位置参数或关键字参数的形式调用:

 

parrot(1000)                                          # 1 positional argumentparrot(voltage=1000)                                  # 1 keyword argumentparrot(voltage=1000000, action='VOOOOOM')             # 2 keyword argumentsparrot(action='VOOOOOM', voltage=1000000)             # 2 keyword argumentsparrot('a million', 'bereft of life', 'jump')         # 3 positional argumentsparrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

 

                        2.    参数列表必须(先书写)位置参数然后才是关键字参数

                                这里关键字必须来自于形参名字

                                形参是否有一个默认值并不重要

                                任何参数都不能被多次赋值——在同一个调用中

                                与位置参数相同的形参名字不能用作关键字

                        3.    *name:    这种类型的参数接受包含了所有没有出现在形式参数列表中的参数值元组

                        4.    **name:    接收一个包含了所有未出现在形式参数列表中的关键字参数的字典

                        5.    一个更全面的实例

                                函数原型:

 

def cheeseshop(kind, *arguments, **keywords):    print("-- Do you have any", kind, "?")    print("-- I'm sorry, we're all out of", kind)    for arg in arguments:        print(arg)    print("-" * 40)     keys = sorted(keywords.keys())        ----打印 关系字 参数字典的内容前先调用 sort() 方法。否则的话,打印参数时的顺序是未定义的。    for kw in keys:        print(kw, ":", keywords[kw]) 调用:cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin",client="John Cleese", sketch="Cheese Shop Sketch")

 

                4.6.3.    可变参数列表

                        1.    两个实例:

def write_multiple_items(file, separator, *args):        ----可变 参数是参数列表中的最后一个, 因为它们将把所有的剩余输入参数传递给函数    file.write(separator.join(args))>>>def concat(*args, sep="/"):        ----任何出现在 *args 后的参数是关键字参数,这意味着,他们只能被用作关键字,而不是位置参数...       return sep.join(args)...>>> concat("earth", "mars", "venus")'earth/mars/venus'>>> concat("earth", "mars", "venus", sep=".")'earth.mars.venus'                          

                4.6.4.    参数列表的分拆

                        1.    分拆元组

 

>>> list(range(3, 6))            # normal call with separate arguments[3, 4, 5]>>> args = [3, 6]>>> list(range(*args))            # call with arguments unpacked from a list[3, 4, 5]

 

                        2.    分拆字典

 

>>> def parrot(voltage, state='a stiff', action='voom'):...     print("-- This parrot wouldn't", action, end=' ')...     print("if you put", voltage, "volts through it.", end=' ')...     print("E's", state, "!")...>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}>>> parrot(**d)-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

 

                4.6.5.    Lambda形式

                        1.    一个实例

>>> def make_incrementor(n):...     return lambda x: x + n        ----类似函数式语言创建短小的匿名函数...>>> f = make_incrementor(42)>>> f(0)42>>> f(1)43                     

                4.6.6.    文档字符串 

                        1.    一个实例

 

>>> def my_function():...     """Do nothing, but document it....                                            ----留白“相当于”是字符串的起始缩进。每一行都不应该有缩进,如果有缩进的话,所有的留白都应该清除掉。...     No, really, it doesn't do anything....     """...     pass...>>> print(my_function.__doc__)Do nothing, but document it.No, really, it doesn't do anything.        ----Python 的解释器不会从多行的文档字符串中去除缩进

 

        4.7.    插曲:编程风格

5.    数据结构   

        5.1.    关于列表更多的内容

                列表对象的所有方法:

                        list.append(x)        ----把一个元素添加到链表的结尾,相当于 a[len(a):] = [x] 。

                        list.extend(L)        ----将一个给定列表中的所有元素都添加到另一个列表中,相当于 a[len(a):] = L 。

                        list.insert(i, x)        ----在指定位置插入一个元素。插在指定元素的前面。返回None

                        list.remove(x)        ----删除链表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。

                        list.pop([i])        ----从链表的指定位置删除元素,并将其返回。如果没有指定索引, a.pop() 返回最后一个元素。元素随即从链表中被删除。

                        list.index(x)        ----返回链表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。

                        list.count(x)        ----返回x在链表中出现的次数。

                        list.sort()        ----对链表中的元素就地进行排序。返回None

                        list.reverse()        ----就地到排链表中的元素。返回None

                5.1.1.    把链表当作堆栈使用

                        1.    利用 list.append(x)和 list.pop([i])

                        2.    链表尾是栈顶

                5.1.2.    把链表当作堆栈使用

                        1.    使用一般列表对象的方法:    效率不高,因为要移动整个

                                从链表头入列:    list.insert(0,x);从列表尾出列:    list.pop()

                                从链表尾入列:    list.append(x);从列表头出列:    list[i] = list[i+1]

                        2.    使用collections.deque,为首位两端快速插入和删除而设计

 

>>> from collections import deque                ----导入这种对象类型>>> queue = deque(["Eric", "John", "Michael"])        ----将一般对象类型转化为queue>>> queue.append("Terry")           # Terry arrives        ----在列表尾部入列>>> queue.append("Graham")          # Graham arrives>>> queue.popleft()                 # The first to arrive now leaves        ----在列表头部出列'Eric'>>> queue.popleft()                 # The second to arrive now leaves'John'>>> queue                           # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])

 

                5.1.3.    列表推导式:    从已有的列表经过对每个元素的重新组合/筛选出新的列表

                        1.    一般方式创建列表:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 

>>> square = [ ]>>> for x in range(10): . . .      squares.append(x**2)

 

                        2.    通过列表推导式

 

>>> squares = [x**2 for x in range(10)]

 

                        3.    通过map的方式

 

>>> squares = map(lambda x: x**2, range(10))

 

                5.1.4.    嵌套的列表推导式:转置3x4的矩阵

                        1.    完全用一般语句实现

 

def row_to_line(matrix):"""a methord to reverse matrix"""transposed = []print(matrix)for i in range(len(matrix[0])):    transposed_row = []    for row in matrix:         transposed_row.append(row[i])    transposed.append(transposed_row)print(transposed)

 

                         2.    部分用列表推导式       

 

 

def row_to_line2(matrix):    """部分用列表推导式"""    transposed = []    for i in range(len(matrix[0])):        transposed.append([row[i] for row in matrix])    print(transposed)

 

                        3.    完全用列表推导式   

 

 def row_to_line3(matrix):     """完全用列表推导式"""    print([[row[i] for row in matrix] for i in range(len(matrix[0]))])

 

                        4.    使用内置函数

 

print(list(zip(*matrix)))                   

 

        5.2.    del语句

                从列表中按给定的索引而不是值来删除一个子项,也可以删除整个变量。

 

>>> a = [1, 2, 3]>>> del a[0,2]>>> a>>> [3]

 

        5.3.    元组与序列(元组是标准序列类型的一种)

                1. 构造元组的形式

                        a.    t = 12345, 54321, 'hello'

                        b.    u = t, (1, 2, 3, 4, 5, 6)

                        c.    v = 'hello',        ----构造单个元素的元组

                2.    元组的输出总是右括号的 

                3.    不能给一个元组的独立元素赋值

                4.    序列拆封

 

>>> t = 12345, 54321, 'hello!' >>> x, y, z = t        ----序列拆封要求左侧的变量数目与序列的元素个数相同。

 

        5.4.    集合

                1. 几个实例

 

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}>>> a = set('abracadabra')>>> b = set('alacazam')>>> a                                  # unique letters in a{'a', 'r', 'b', 'c', 'd'}>>> a - b                              # letters in a but not in b{'r', 'd', 'b'}>>> a | b                              # letters in either a or b{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}>>> a & b                              # letters in both a and b{'a', 'c'}>>> a ^ b                              # letters in a or b but not both{'r', 'd', 'b', 'm', 'z', 'l'}

 

                2.    通过推导式构建集合

 

>>> a = {x for x in 'abracadabra' if x not in 'abc'}>>> a{'r', 'd'}

 

        5.5.    字典(联合内存/联合数组)

                1.    属于python内建数据类型    

                2.    索引方式:    序列是以整数为索引,字典以关键字为索引

                3.    关键字:    

                            a.    任意不可变类型,比如字符串或数值

                            b.    元组如果包含可变对象不可以作为关键字

                            c.    链表不能作为关键字(因为可以改变)

                4.    del:    删除键值对

                5.    list(d.key()) :    将返回一个字典中所有关键字组成的无序列表

                4.    sorted(d.key()):     将返回一个字典中所有关键字组成的有序列表

                6.    in:    检查字典中是否存在某个键值

        5.6.    循环技巧

 

  • iteritems()    :    字典循环中键和值同时解读

 

 

>>> knights = {'gallahad':'the pure','robin':'the brave'};>>> for k, v in knights.items():    print(k,v) robin the bravegallahad the pure
  • enumerate()    :    序列循环中索引位置和对应值

>>> for i, v in enumerate(['tic', 'tac', 'toe']):    print(i,v)  0 tic1 tac2 toe

 

 

  • zip()    :    同时循环两个或更多的序列

>>> questions = ['name', 'quest', 'favorite color'];>>> answers = ['lancelot', 'the holy grail', 'blue'];>>> for q, a in zip(questions, answers):    print('what is your {0}? It is {1}.'.format(q,a))  what is your name? It is lancelot.what is your quest? It is the holy grail.what is your favorite color? It is blue.
  • reversed()    :    逆向循环序列

>>> for i in reversed(range(1,10,2)):    print(i)  97531
 
  • sorted()    :    它不改动原序列,而是生成一个新的已排序的序列

>>> for f in sorted(set(basket)):    print(f)  applebananaorangepear

 

posted @ 2014-09-25 18:07  Neuromancer  阅读(3232)  评论(0编辑  收藏  举报