python笔记

Tutorial
1. Python可以带命令行启动,具体查看文档


2. 注释使用#,
    指定文件编码使用:# coding[=:]\s*([-\w.]+)
    

3.  可以设置python启动脚本,详见tutorial 2.2.4,2.2.5


4.  在交互模式下,上次计算的结果被保存在变量[_]中


5.  字符串(字符串是不可变的)
    5.1 'a' * d  # 表示将'a'重复五次,即得到'aaaaa'

    5.2 使用Slice indices得到子串:str[0:2],str[:2], str[2:]
        str[-1]  # The last character
        str[-2]  # The last-but-one character
        str[-2:] # The last two characters
        str[:-2] # Everything except the last two characters

    5.3 求长度:使用len(str`)
    

6.  Unicode
        literal: 使用前缀u,如:u'hello world',
        也可以再字符串中使用Unicode转换符:\u

    6.1 str()可以将Unicode转换为ANSI,但是它只可以转换ANSII字符,即0-127

    6.2 unicode()可将ansi字符转换为unicode,它也只可以转换ANSII字符

    6.3 str = u'你好'.encode('utf-8')
        unicode(str, 'utf-8')

    
7.  Lists
        l1 = [1, 2, 3]
        l2 = l1
        l2[0] = 0  # l1[0] == 0 too,即l2 = l1是传引用

    7.1 浅拷贝  可使用slice indices:l2 = l1[:]

    7.2 使用slice indices改变list
        a = [1, 2, 3, 4]
        a[0:2] = [5, 6]  # replace, a == [5, 6, 3, 4]
        a[0:2] = []      # remove, a == [3, 4], 等价于 del a[0:2]
        a[1:1] = [5, 6]  # insert, a == [3, 5, 6, 4]
        a[:0] = a        # insert, 在头部插入a 自身
        a[len(a):] = a   # insert, 在末尾插入a自身,等价于a.extend(a)
        a[:] = []        # clear the list, 等价于 del a[:]。若del a, 则删除了a,  此后a不可用

    7.3 成员方法
        a.append(x)    # equivalent to a[len(a):] = [x]
        a.extend(L)    # equivalent to a[len(a):] = L  ,L是list类型
        a.insert(i, x) # 在i之前插入x
        a.remove(x)    # remove the first item whose value is x
        a.pop([i])     # remove 索引i处的元素,若没有指定i,则移除最后一个元素。返回被移除的元素。
        a.index(x)     # 返回list中第一个x的索引
        a.count(x)     # 返回list中x的个数
        a.sort()       # 排序
        a.reverse()    # 颠倒list中的元素

    7.4 模拟stack 和 queues
        使用append和pop模拟stack

        对于队列,
        from collections import deque
        queue = deque(['one', 'two'])
        queue.append('three')  # insert end
        queue.popleft()        # remove first

    7.5 build in functions (filter, map, reduce)
        filter(function, sequence)  # returns a sequence ,包含所有function(item) == True的元素
            如果sequence的类型是string 或 tuple,则返回类型不变,否则,返回list
        map(func, sequence)  # 为sequence的每个item调用func(item),返回 list of return values。
            def cube(x):return x*x*x
            map(cube, range(3))          # [0, 1, 8]
            可以向map中传递多个sequence
            def add(x, y): return x + y
            map(add, range(3), range(3)) # [0, 2, 4]
        reduce(func, sequence) # 对sequence中的所有元素进行运算
            def add(x, y):return x + y
            reduce(add, range(3)) # 3

    7.6 list comprehensions 链表推导,一种简洁的方式创建链表
        squares = [x**2 for x in range(3)]       # [0, 1, 4],等价于map(lambda x:x**2, range(3))
        squares = [x for x in range(3) if x > 1] # [2]
        squares = [(x, y) for x in range(2) for y in range(2)]  # [(0, 0), (0, 1), (1, 0), (1, 1)]

        Nested List Comprehensions


8. 循环
    8.1 while, while循环无所不能

    8.2 for, python中的for语法,for i in list:

    8.3 使用range(),
        range(3)         # 连续的序列 [0, 1, 2]
        range(3, 6)      # 指定序列开头和结尾 [3, 4, 5]
        range(0, 10, 3)  # 指定步长 [0, 3, 6, 9]
    

9. pass 语句
    while True:
    pass # 空语句

    class MyEmptyClass:
    pass # 用作占位符,因为类和方法必须有实现
    

10. 定义函数
        def funcname(params):
        "doc string" # 可选
        # do you work

    10.1 默认参数的副作用
        def f(a, L=[]): # L的默认参数是可变类型,会被随后的调用共享
            L.append(a)
            return L

        print f(1)  # [1]
        print f(2)  # [1, 2]
        print f(3)  # [1, 2, 3]

        若不想使之共享,可以这样修改:
        def f(a, L=None):
            if L is None:
            L = []
            L.append(a)
            return L

    10.2 Keyword Arguments
        函数的参数可以将之视为一个字典,在进行函数调用时,可以指定想要传递的参数。
        def func(one, two='two', three = 'three'):
            print one, two, three

        func('one')  # one two three
        func('three', three='one')  # three two one
        func(two = 'one', one = 'two') # two one three

    10.3 将tuple,dictionary作为参数
        若名字格式为 *name, 则name接受一个tuple,
        若名字格式为 **name, 则name接受一个dictionary

        def func(*name):
            for arg in name:
        print arg,

        func('hello', ', ', 'world')  # hello, world

        def func(**name):
            for key in name.keys():
            print key, name[key]

        func(one='hello', two='world') 
            # two world
            # one hello

    10.4 Unpacking Argument List
        range(3, 6) # [3, 4, 5]
        args = [3, 6]
        range(*args)  # 参数从list中获取,[3, 4, 5]

        def func(one, two='two', three = 'three'):
            print one, two, three

        d = {'one':'two', 'two':'three', 'three':'one'}
        func(**d)  # two three one


11. Tuples元组
    建立空tuple:t = ()
    建立一个元素的tuple: t = (1, ) # 1后面的逗号是必需的
    Tuple packing   :   t = 1, 2, 3  # 等价于t = (1, 2, 3)
    Tuple unpacking :   x, y, z = t  # 为x, y, z赋值


12. Set 集合
        Set是无序的容器,其中不能包含重复的元素。
        它可以进行 求并集,交集,差集,对称差集

    12.1 创建Set
        可以从其他集合中创建set,如list, str等
        nums = [1, 2, 1, 2]
        sn = set(nums)     # set([1, 2])

        a = set('banana')   # set(['a', 'b', 'n'])
        b = set('apple')    # set(['a', 'p', 'e', 'l'])
        a | b               # union, set(['a', 'p', 'b', 'e', 'l', 'n'])
        a & b               # intersection, set(['a'])
        a ^ b               # symmetric difference, set(['b', 'e', 'l', 'n', 'p'])


13. Dicdionarys 字典
        字典中保存的是 key:value对,以花括号包围之,如:
        d = {1:'1', 2='2', 3:'3'}

        d.keys()    # 返回key列表,[1, 2, 3]
        d.values()  # 返回value列表,['1', '2', '3']

        1 in d      # 判断 1 是否是d的一个key,True
        del d[1]    # 删除 key 为1的项

    13.1 使用dict()构造器
        d = dict([('ome', '1'), ('two', '2'), ('three', '3')]) # {'one':'1', 'two':'2', 'three':'3'}
        如果key都是字符串的话,也可以这样构建:
        d = dict(one = '1', two = '2', three = '3')  # {'one':'1', 'two':'2', 'three':'3'}
        

14. 循环技术
    14.1 遍历字典时,同时获取key所对应的value
        for k, v in dict.iteritems():
            print k, v

    14.2 enumerate(), 遍历序列时,同时获取index所对应的value
        for i, v in enumerate(['one', 'two', 'three']):
            print i, v

    14.3 zip(), 同时遍历两个,或更多的序列
        num = [1, 2, 3]
        str = ['one', 'two', 'three']
        for n, s in zip(num, str):
            print n, s

        上边代码的输出:
        # 1 one
        # 2 two
        # 3 three

        zip(num, str)的返回值为元组的列表:[(1, 'one'), (2, 'two'), (3, 'three')]

    14.4 reversed(), 逆序遍历一个序列
        for i in reversed(xrange(1, 10 , 2))
            print i

    14.5 sorted(), 按照排序后的顺序遍历一个序列
        num = [3, 2, 1]
        for i in sorted(num):
            print i


15. Module 模块
    一个模块就是一个包含python语句的文件,文件名为 模块名 + .py扩展名。
    在文件中可以使用全局变量__name__获取模块名。

    15.1 将模块作为一个脚本执行
        在命令行中:python module_name.py
        此时这个模块中的代码将会得到执行,并且,python会将此模块名__name__设置为 '__main__'
        可以在模块中添加如下代码,使模块只在作为脚本时才得到执行:
            if __name__ == '__main__'
                import sys
                # your code

    15.2 module搜索路径
        若一个名为hello的模块被引入,解释器首先会搜索内建模块,
        如果没有找到,它会在若干目录中搜索hello.py, 这些目录名由sys.path指定。
        sys.path从下面这些位置初始化:
            1. .py所在目录
            2. PYTHONPATH
            3. 安装目录

    15.3 package的概念,管理module名字空间
        详见Tutorial 6.4
        package实际上是一个文件夹,文件夹的名字即是包名;
        但是,文件夹下需包含一个__init__.py文件,python才会将之视为一个package。
原文地址:https://www.cnblogs.com/hdtianfu/p/2404168.html