《python语言及其应用》—读书笔记
想对python进行一次梳理,于是读《Python语言及其应用》部分章节,并记录于此。
目录:
1 Python初探
2 Python基本元素:数字、字符串和变量
3 Python容器:列表、元祖、字典与集合
4 Python外壳:代码结构
5 Python盒子:模块、包和程序
6 对象和类
1 Python初探
2 Python基本元素:数字、字符串和变量
2.1 变量、名字和对象
- 变量名仅能包含字母、数字、下划线,只能以字母、下划线开头
2.2 数字
- 幂运算:2 ** 3 = 8
整数
- divmod(a, b),得元组(商,余数)
基数
- 0b、0B表二进制
- 0o、0O表八进制
- 0x、0X表十六进制
类型转换
- 强制类型转换:int(a), str(a), float(a). 特别地:int强制转换字符串时,只能转换仅含一个整数的字符串如‘23’,‘23.1’、‘1e4'等非整数不行
- 一个int型有多大
- python2中int型32位,long64位;python3中无long型,int型可存储超过64位
2.3 字符串
使用引号创建
- 用一对单引号、双引号、三元引号(用于创建多行字符串,保留换行和空格)创建字符串
- python允许创建空字符串
使用转义
- 在字符串中用转义字符表示单双引号,\'、\"
使用分片
- 字符串不可变,无法在原字符串中插入字符或改变指定位置字符
- [start: end: step]分片,从start到end -1
- 分片时小于起始位置偏移量当做0,大于终止位置偏移量当做-1
使用split()分割
>>>todos = 'get gloves, get mask' >>>todos.split(',') ['get gloves', 'get mask']
- 若不制定分隔符,split()将默认使用空白字符—换行符、空格、制表符
使用join()合并
>>>c_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster'] >>>c_string = ','.join(c_list) 'Yeti, Bigfoot, LOCH Ness Monster'
熟悉字符串
>>> poem = '''All that doth flow we cannot liquid name or else would fire and water be the same;''' >>>#poem第一次出现单词or的位置 >>>poem.find('or') 41 >>>#最后一次出现or的位置 >>>poem.rfind('or') 41 >>>#or在poem中共出现几次 >>>poem.count('or') 1
大小写与对齐方式
>>>setup = 'a duck goes into a bar...' >>>#删除字符串收尾的'.' >>>setup.strip('.') 'a duck goes into a bar' >>>#字符串首字母变成大写 >>>setup.capitalize() 'A duck goes into a bar...' >>>#所有单词开头变成大写 >>>setup.title() 'A Duck Goes Into A Bar...' >>>#所有字母变成大写 >>>setup.upper() 'A DUCK GOES INTO A BAR...' >>>#所有字母变成小写 >>>setup.lower() 'a duck goes into a ba..'
使用replace()替换
- 使用replace()函数可以进行简单子串替换,需传入参数包括:需替换的、新的、替换多少处(默认1)
>>>setup.replace('duck', marmoset') 'a marmoset goes into a bar...'
3 Python容器:列表、元祖、字典与集合
3.1 列表和元祖
3.2 列表
>>>marxes = ['Groucho', 'Chico', 'Harpo'] >>>others = ['Gummo', 'Karl'] >>>#使用append()添加元素至尾部 >>>marxes.append('Zeppo') ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>>#使用extend()或+=合并列表 >>>marxes.extend(others) ['Groucho', 'Chico', 'Harpo', 'Zeppo', 'Gummo', 'Karl'] >>>#使用insert()在制定位置插入元素 >>>marxes.insert(3, 'Gummo') ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] >>>#使用del删除指定位置元素 >>>del marxes[-1] ['Groucho', 'Chico', 'Harpo', 'Gummo'] >>>#使用remove()删除具有指定值的元素 >>>marxes.remove('Gummo') ['Groucho', 'Chico', 'Harpo'] >>>#使用pop()获取并删除制定位置的元素(默认-1) >>>marxes.pop() 'Harpo' >>>marxes ['Groucho', 'Chico''] >>>#使用index()查询具有特定值的元素位置 >>>marxes.index('Chico') 1 >>>#使用count()记录特定值出现的次数 >>>marxes.count(''Chico') 1 >>>#使用join()将列表转换为字符串 >>>','.join(marxes) 'Groucho, Chico' >>>#使用sort()重新排列元素 >>>#列表方法sort()会对原列表进行排序,改变原列表内容 >>>#通用方法sorted()则会返回排好序的列表副本,原列表内容不变 >>>#使用len()获取列表长度 >>>#使用=赋值,使用copy()复制 >>>a = [1, 2, 3] >>>b = a >>>a[0] = 'change' >>>a ['change', 2, 3] >>>b ['change', 2, 3] #b、d、d都是a的复制,会新创内存复制 >>>a =[1, 2, 3] >>>b = a.copy() >>>c = list(a) >>>d = a[:] >>>a[0] = 'change' >>>a ['change', 2, 3] >>>b b = [1, 2, 3] >>>c c = [1, 2, 3] >>>d d = [1, 2, 3]
3.3 元祖
定义元祖真正靠的是每个元素后面的逗号(但如果习惯加一对括号也可以)
>>>#创建空元祖 >>>empty_tuple = () >>>empty_tuple () >>>#创建包含一个元素的元祖 >>>one_marx = 'Groucho', >>>#等价于one_marx = ('Groucho',) >>>one_marx ('Groucho',) >>>#创建包含多个元素的元祖 >>>marx_tuple = 'Groucho', 'Chico', 'Harpo' >>>marx_tuple ('Groucho', 'Chico', 'Harpo') >>>#元祖解包(提取出字符串) >>>a, b, c = marx_tuple >>>a 'Groucho' >>>b 'Chico' >>>c 'Hamo'
3.4 字典
- 字典中的元素是0个或若干个键值对
- 使用empty_dict = {}创建空字典
- 可对任何包含双值子序列使用dict()转换为字典
>>>#包含双值元祖的列表: >>>lot = [('a', 'b'), ('c', 'd'), ('e', 'f')] >>>dict(lot) {'c': 'd', 'a': 'b', 'e': 'f'} >>>#包含双值列表的元祖 >>>tol = (['a', 'b'], ['c', 'd'], ['e', 'f']) >>>dict(tol) {'c': 'd', 'a': 'b', 'e': 'f'} >>>#双字符的字符串组成的列表 >>>los = ['ab', 'cd', 'ef'] >>>dict(los) {'c': 'd', 'a': 'b', 'e': 'f'} >>>#双字符的字符串组成的元祖 >>>tos = ('ab', 'cd', 'ef') >>>dict(tos) {'c': 'd', 'a': 'b', 'e': 'f'}
- 字典常用操作如下
>>>pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Idle': 'Eric'} >>>#使用update()合并字典(相同的键对应的值会被取代) >>>others = {'Marx': 'Groucho', 'Idle': 'Moe'} >>>pythons.update(others) >>>pythons {'Chapman': 'Graham', 'Cleese': 'John', 'Idle': 'Moe', 'Marx': 'Groucho'} >>>#使用del删除具有指定建的元素 >>>del pythons['Marx'] >>>pythons {'Chapman': 'Graham', 'Cleese': 'John', 'Idle': 'Moe'} >>>#使用clear()删除所有元素 >>>pythons.clear() >>>pythons {} >>>pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Idle': 'Eric'} >>>#使用in判断键是否存在 >>>'Chapman' in pythons True >>>#使用[key]获取元素时,若不存在该key,会报错.避免这种情况,方法如下 >>>#方法1, 先用in判断是否存在,再取值 >>>#方法2, 使用pythons.get('Chapman') >>>#使用keys()获取所有键 >>>pythons.keys() dict_keys(['Chapman', 'Cleese', 'Idle']) >>>#使用values()获取所有值 >>>pythons.values() dict_values(['Graham', 'John', 'Eric']) >>>#使用items()获取所有键值对 >>>pythons.items() dict_items([('Chapman', 'Graham'), ('Cleese', 'John'), ('Idle', 'Eric')]) >>>list(pythons.items()) [('Chapman', 'Graham'), ('Cleese', 'John'), ('Idle', 'Eric')] >>>#使用=赋值,使用copy()复制,与列表同理
3.5集合
>>>#使用set()创建集合 >>>empty_set = set() >>>empty_set set() >>>#set()将其他类型转换为集合 >>>set('letters') {'l', 'e', 't', 'r', 's'} >>>set(['Dasher', 'Dancer', 'Prancer']) {'Dasher', 'Dancer', 'Prancer'} >>>#建立一个叫drinks的字典,对应的value为饮料的成分 >>>drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua', 'vodka'}, 'white russian': {'cream', 'kahlua', 'vodka'}, 'manhattan': {'rye', 'vermouth', 'bitters'}, 'screwdriver': {orange juice', 'vodka'} } >>>#哪种饮料含有伏特加 >>>for name, contents in drinks.items(): ... if 'vodka' in contents: ... print(name) screwdriver martini black russian white russian >>>#含有伏特加,但不含乳糖和艾酒 >>>for name, contents in drinks.items(): ... if 'vodka' in contents and not ('vermouth' in contents or 'cream' in contents): ... print(name) screwdriver black russian >>>#合并及运算 >>>a = {1, 2} >>>b = {2, 3} >>>#得到两个集合共有的元素 >>>a & b {2} #取并集 >>>a | b {1, 2, 3}
4 Python外壳:代码结构
4.5 使用for迭代
字符串、列表、元组、字典、集合等都是可迭代的对象
对一个字典直接进行迭代,返回字典的键
使用zip()函数配对
>>>english= ‘Monday', 'Tuesday', 'Wednesday' >>>french = 'Lundi', 'Mardi', 'Mercredi' >>>list( zip(english, french) ) [('Monday', 'Lundi'), ('Tuesday', 'Mardi'), ('Wednesday', 'Mercredi')] >>>dict( zip(english, french) ) {'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi'}
range()函数返回在特定区间的自然数序列,start默认为0,stop必须指定,step默认为1
4.6 推导式
- 列表推导式
>>>#[expression for item in iterable] >>>number_list = [number - 1 for number in range(1, 6) if number % 2 == 1] >>>number_list [0, 2, 4]
- 字典推导式
- 集合推导式
- 元组没有推导式,将列表推导式中的方括号变成圆括号形成生成器
4.7 函数
- 默认参数值在函数被定义时已经计算出来。我们经常犯的一个错误是把可变的数据类型(例如列表或者字典)当作默认参数值
#buggy定义时这里的空列表已分配出来 >>>def buggy(arg, result=[]): ... result.append(arg) ... print(result) >>>buggy('a') ['a'] >>>buggy('b') ['a', 'b']
- 使用*收集位置参数
>>>#当参数被用在函数内部,星号将一组可变数量的位置参数集合成参数值的元组 >>>def print_args(*args): ... print('include:', args) >>> print_args(3, 2, 1, 'wait') inlcude: (3, 2, 1, 'wait')
- 使用**收集关键字参数
>>>#使用两个星号可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字典的值 >>>def print_kwargs(**kwargs): ... print('include:', kwargs) >>>print_kwargs(wine='merlot', entree='mutton') include: {'wine': 'meriot', 'entree': 'mutton'}
- 闭包
>>>#内部函数 >>>def knights(saying): ... def inner(quote): ... return "say: '%s'" % quote ... return inner(saying) >>>#闭包 >>>#inner2()直接使用外部的saying参数,而不是通过另外一个参数获取 >>>#knights2()返回值为inner2函数,而不是调用它 >>>def knights2(saying): ... def inner2(): ... return "say: '%s'" % saying ... return inner2 >>>a = knights2('Duck') >>>a() "say: 'Duck'"
- 匿名函数:lambda()函数
func = lambda word: word.capitalize()
4.8 生成器
4.9 装饰器
- 不改变源代码的情况下修改已存在的函数
>>>#定义一个装饰器 >>>def square_it(func): #输入参数为函数 ... def new_function(*args, **kwargs): #*args **kwargs提取所有参数 ... result = func(*args, **kwargs) #调用func得到其返回值 ... return result ** 2 #装饰器处理func返回值 ... return new_function #闭包 >>>#用装饰器装饰一个函数 >>>@square_it ...def add_ints(a, b): ... return a + b >>>add_ints(3, 5) 64
5 Python盒子:模块、包和程序
5.3 模块和import语句
- 一个模块仅是Python代码的一个文件
5.4 包
- 将多个功能相近模块组织成文件层次,称为包(如numpy是一个包)。包中必须包含__init__模块(可以为空)
6 对象和类
6.2 使用class定义类
- 类的定义中,__init__并不是必需的。只有当需要区分由该类创建的不同对象时,才需要指定__init__方法
class Persong(): def __init__(self): pass
6.3 继承
- 在新类里面定义额外需要的方法(与父类不一样的方法名),或覆盖父类的方法(与需要覆盖的父类方法名同名)
class Car(): pass class Yugo(Car): pass
6.6 使用super从父类得到帮助
- 在子类中定义__init__方法时,父类的__init__方法会被覆盖。所以在子类中,弗雷德初始化方法若需要,要显示调用
class EmailPerson(Person): def __init__(self, name, email): super().__init__(name) #不需再传入self参数 self.email = email
6.8 使用属性对特性进行访问和设置
- 为对象编写setter和getter方法
>>>class Duck(): ... def __init__(self, input_name): ... self.hidden_name = input_name ... @property ... def name(self): ... print('inside the getter') ... return self.hidden_name ... @name.setter ... def name(self, input_name): ... print('inside the setter') ... self.hidden_name = input_name >>>fowl = Duck('Howard') >>>fowl.name inside the getter 'Howard' >>>fowl.name = 'Donald' inside the setter >>>fowl.name inside the getter 'Donald'
6.9 使用名称重整保护私有特性
- Python对那些需要刻意隐藏在类内部的特性有自己的命名规范:由连续的两个下划线开头'__'
#这样就不能在类外直接调用 对象.__name >>>class Duck(): ... def __init__(self. input_name): ... self.__name = input_name ...
6.10 方法的类型
- 实例方法:首个参数为self
- 类方法:首个参数为cls,用前缀修饰符@classmethod指定
- 静态方法:参数无要求,用前缀修饰符@staticmethod指定
8 数据的归宿
8.1 文件输入/输出
- fileobj = open(filename, mode)将文件指针载入内存,供读写调用。最后需要关闭文件
1. mode的第一个字母表明对其的操作:
r 表示读模式
w 表示写模式。如果文件不存在则新创建,如果存在则重写新内容
x 表示在文件不存在的情况下新创建并写内容
a 表示如果文件存在,在文件末尾追写内容
2. mode的第二个字母是文件类型::
t(或省略不写) 代表文本类型
b 代表二进制文件
- 使用write()写文本文件
>>>poem = 'this is an example' >>>#将其写入文件'relativity'中 >>>fout = open('relativity', 'wt') >>>fout.write(poem) 19 >>>fout.close()
未完...