Python基本语法

基本容器类型

list

>>>classmates = ['Tom','Peter']
>>>classmates
['Tom','Peter']
classmates.append('AMS') #想尾插入
classmates.insert(1,'a')#向指定位置插入
classmates.pop()#删除末尾
classmates.pop(1)#删除指定位置

tuple

tuple使用时使用(),且不能改变元素

dic

dic与map基本一致

d = {'s":2,'a':3}
d.pop('s')#会删除's'以及对应的值

set

声明并定义一个set必须提供一个list

s=set(['a','b'])
s.add('c')
s.remove('c')

高级特性

列表生成式

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

还可以两层调用

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

生成器generator

只要将一个列表生成式的[]换成(),就创建了一个生成器

生成器不耗用太多内存,仅仅在要使用时生成元素

杨辉三角:

def add(n):
    L=[1]
    while True:
        yield L
        L = [L[x]+L[x+1]for x in range(len(L)-1)]
        L.insert(0,1)
        L.append(1)
        if len(L) > n:
            break

斐波契利数列

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

使用生成器时用Iterator即可

迭代器

将一个非Iterator对象转换为Iterator对象,它们表示惰性计算对象

>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True

函数式编程

map

>>> def f(x):
...     return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

map的第一个参数为函数对象,第二个参数为使用对象

reduce累积计算

>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

map与reduce运用实例

from functools import reduce
def str2int(s):
    def fn(x,y):
        return x * 10 + y
    def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    return reduce(fn, map(char2num, s))

filter

>>> def is_odd(n):
...     return n%2==1
...
>>> list(filter(is_odd,[1,2,3,4,5,6]))
[1, 3, 5]

查找素数

def odd_():
    n = 1
    while True:
        n = n + 2
        yield n
def lam_odd(n):
    return lambda x : x % n >0
def result():
    yield 2
    it = odd_()
    while True:
        n = next(it)
        yield n 
        it = filter(lam_odd(n),it)
for n in result():
    if n < 50:
        print(n)
    else:
        break

返回函数

def count():
    def f(j):
        def g():
            return j*j
        return g 
    fs = []
    for i in range(1,4):
        fs.append(f(i))
    return fs
f1,f2,f3 = count()
n1,n2,n3 = f1(),f2(),f3()
print(n1,n2,n3)

面向对象高级特性

使用slots

class Student(object):
    __slots__ = ('name', 'age') ## 用tuple定义允许绑定的属性名称

使用@property

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

s = Student()
s.score = 60
print('s.score =', s.score)
## ValueError: score must between 0 ~ 100!
s.score = 9999

str与repr

class Student(object):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return 'Student object (name=%s)' % self.name
    __repr__ = __str__

这样使用print()方法或在交互环境中使用时,可以得到自己想要的结果

iter

>>> class Fib(object):
...     def __init__(self):
...             self.a,self.b = 0,1
...     def __iter__(self):
...             return self
...     def __next__(self):
...             temp = self.a
...             self.a = self.a + self.b
...             self.b = temp + self.b
...             if self.a>50:
...                     raise StopIteration()
...             return self.a
...
>>> for i in Fib():
...     print(i)
...
1
2
4
8
16
32

错误异常处理

处理异常

class TEST(object):
    def __init__(self,s):
        self.s = s
    def foo(s):
        return 10 / int(s)
    def bar(s):
        return foo(s) * 2

    def main(self):
        try:
            bar(self.s)
        except Exception as e:
            print('Error:', e)
        finally:
            print('finally...')

调试

def foo(s):
    n = int(s)
    assert n != 0, 'n is zero!'
    return 10 / n

启动Python解释器时可以用-0参数来关闭assert

IO编程

文件读写

with open('test.txt','r') as e :
    print(e.read())
for i in e.readlines():
    print(lines.strip())#进行行读写

如果要读取二进制文件如图片视频等,用rb方式打开即可

f = open('d.jpg','rb')

下面介绍写入方法

with open('test.txt','w') as f:
    f.write('hello')

操作目录

>>> import os
>>> os.path.abspath('')
'E:\\test'
>>> os.path.join('E:\\test','new')
'E:\\test\\new'
>>> os.mkdir('E:\\test\\new')
>>> os.rmdir('E:\\test\\new')

重命名文件,删除文件

>>> os.rename('新建文本文档.txt','呵呵.txt')
>>> os.remove('呵呵.txt')

序列化

如果想另数据在网络或磁盘上传播,可以使用序列化

pickle

>>> import pickle
>>> d = dict(name = 'Bob',age = 20)
>>> f = open('py.txt','wb')
>>> pickle.dump(d,f)
>>> f.close()
>>> f = open('py.txt','rb')
>>> d = pickle.load(f)
>>> f.close()
>>> d
{'name': 'Bob', 'age': 20}

json

后续补充

多进程与多线程

多进程

multiprocessing模块提供了一个Process类

from multiprocessing import Process
import os

def run_proc(name):
    print('Run child process %s(%s)'%(name,os.getpid()))

if __name__ == '__main__':
    print('Parent process %s.'%os.getpid())
    p = Process(target = run_proc,args=('test',))
    print('Child process will start')
    p.start()
    p.join()
    print('end')

其他内容因为暂时用不到,以后进行补充,暂时不用