2018 年 7 月 9 日 10:58:18
摘要: 在阅读 python 相关书籍中, 对其进行简单的笔记纪要. 旨在注意一些细节问题, 在今后项目中灵活运用, 并对部分小 notes 进行代码标注.(本文原创, 转载注明出处: Python 读书笔记: 70 个注意的小 Notes)
Python 读书笔记
1 python 始终记录变量最新值.
2 变量应简短且具有描述性, 如 student_name 等.
3 变量名推荐小写.
4 单双引号括起来的, 字符串可以包含引号和撇号. 用法:"this's a cup"
5 title() 将每个单词的首字母都改为大写. 用法: str.title()
6 upper() 将字符串转化为大写. 用法: str.upper()
7 lower() 将字符串转化为小写. 用法: str.lower()
8 空白泛指任何非打印字符. 如空格, 制表符和换行符.
9 rstrip() 剔除字符串末尾空白. 用法: str.rstrip()
10 lstrip() 剔除字符串开头空白. 用法: str.lstrip()
11 strip() 剔除字符串两端空白. 用法: str.strip()
12 Python 使用两个称号表示乘方. 用法: 3 ** 2
13 编程理念. Python 之禅: import this
14 list 中使用逗号来分割其中的元素.
15 list 索引 - 1 返回最后一个元素列表,-2 以此类推. 用法: list[-3:]
16 list[0] = 'update' 修改列表元素
17 list.append('add') 列表中添加元素
18 list.insert(0.'insert') 列表中指定位置插入元素
19 del list[0] del 元素删除 list 元素
20 newlist = list.pop() 方法 pop() 删除元素
21 从列表中删除元素且不再使用用 del 方法, 删除元素后还有可能用选择 pop()
22 list.remove('element') 根据值移除第一个指定的元素, 可接着使用.
23 sort() 列表按照字母永久性排序. 如: list.sort()
24 sort() 列表按照字母相反的排序. 如: list.sort(reverse=True)
25 reverse() 反转列表元素排序. 用法: list.reverse()
26 for 循环遍历时候选择有意义的名称. 用法: for cat in cats:
27 range() 生成一系列数字. 用法: numbers= list(range(1,11,2))
28 list 的内建统计函数. 用法: min(list)/max(list)/sum(list)
29 python 的切片功能. 用法: list[0:3]/list[:]/list[-3:]/list[:9]
30 list 复制. 用法: new_foods = old_food[:]
31 元组包括一些列不可修改的元素且用圆括号标识. 用法: tulple = (2,3)
32 检查是否相等时不考虑大小写. 用法: str.lower() == 'somestr'
33 使用 and 检查多个条件. 用法: condition1>=1 and condition2>=2 and ...
34 使用 or 检查多个条件. 用法: condition1>=1 or condition2>=2 or ...
35 使用多个列表. 用法:
- list1 = ['1','2','3','4']
- list2 = ['1','4']
- for l2 in list2:
- if l2 in list1:
- go()
- else:
- pass
36 比较运算符两边各添加空格, 便于可读性. 用法: if age> 40:
37 dict 修改值, 用法: dict['key'] = value
38 dict 删除键值对, 用法: del dict['key']
39 字典的遍历, 用法:
- for key,value in dict.items():
- for key in dict:
- for key in dict.keys():
- for value in dict.values():
- for value in set(dict.values()): # 遍历字典的无重复值
40 字典列表, 用法:
- dict1 = ['key1':'values1','key2':'values2']
- dict2 = ['key1':'values3','key2':'values4']
- dict3 = ['key1':'values5','key2':'values6']
- dicts = [dict1,dict2,dict3]
- for dict in dicts:
- pass
41 字典中存储列表, 用法:
- dict1 = {'key1':'values1','key2':['values1','values2']}
- for dict in dict1['key2']:
42 字典中存储字典, 用法:
- dicts = {
- 'keys1':{'key1':'values1','key1':'values2''key1':'values3'},
- 'keys2':{'key2':'values2','key2':'values2''key2':'values3'}
- }
43 input 接收用户输入, 用法: message = input('user input some values!')
44 % 取模运算判断奇偶, 用法:
- if (4 % 3) == 0:
- print('偶数'):
- else:
- print('奇数')
45 while 循环的常规用法:
- current_number = 1
- while current_number <= 10:
- print('current_number')
- current_number += 1
46 while 循环使用标志的用法:
- flag = True
- while flag:
- message = input(prompt)
47 列表之间移动元素, 用法:
- while list[]:
- newlist.append(list[].pop())
48 删除特定的元素, 用法:
- while element in list:
- list.remove(element)
49 形参与实参的理解, 用法:
- def method(username): # username 形参
- method('zhangsan') # zhangsan 实参
50 位置参数, 用法:
- def describe(name,age):
- describe('zhangsan',22) # 参数位置对应传递
51 关键字实参是传递函数的名称 - 值对, 用法:
- def describe(name,age):
- describe(name='zhangsan',age=22) # 关键字实参
- describe(age=22,name='zhangsan') # 关键字实参, 位置不重要
52 形参设置默认值, 用法: def describe(name='lisi',age):
53 返回值, 用法:
- def describe(name='lisi',age):
- des = name + str(age)
- return des # 可以返回字典, 列表等形式
54 列表参数, 用法:
- lists = ['huangsan','lisi','wangjun','denghui']
- def cats_name(lists):
- for list in lists:
- print("'my love is :\t'+list".title())
55 传递任意参数, 用法: def cats_name(*cats): # 可以传递多个形参
56 位置实参和任意数量实参:
- def cats_name(parament1,parament2,*cats): # 可以传递多个形参
- cats_name(para1,para2,para3,para4,...)
57 任意实参和关键字实参, 用法:(cats.py)
- def cats_name(parament1,parament2,**cats): # 可以传递多个形参
- cats_name(para1,para2,para3,newname=para4,...)
58 导入整个模块, 用法:
- import cats
- cats.cats_name(para1,para2,para3,newname=para4,...)
59 导入特定的函数, 用法: from nltk import map_tag as mt
60 导入模块所有函数, 用法: from nltk import *
61 形参默认时, 两边不能为空, 用法: def function_name(parament_0,parament_1='default')
62 类的命名是驼峰型即首字母大写.
63 __init__(self,papa1,para2): 避免 python 默认方法跟普通方法名称冲突, self 必不可少
, 必须位于其他形参的前面, 指向实例本身.
64 类的继承, 用法:
- # 父类
- class Animal():
- def __init__(self,name,age):
- self.name = name
- self.age = age
- def animal_call(self):
- print('this is'+self.name.title()+'call.')
- # 子类
- class Cat(Animal):
- def __init__(self,name,age,color):
- super().__init__(name,age)
- self.color =color
- def cat_color(self):
- my_color = 'the cat is'+self.color
- print(my_color)
- return my_color
- if __name__ == '__main__':
- cat = Cat('tom',22,'blue')
- cat.animal_call()
- strs=cat.cat_color()
65 几种类的导入方式, 用法:
- from cat import Cat # 导入单个类
- from cat import Animal,Cat # 导入多个类
- from cat # 导入整个模块
- from cat import * # 导入所有类
66 读取文本文件, 并删除字符串始末空白, 用法: my_str = line.strip()
67 opem() 自动创建文件路径, 若路径不存在时候.
68 异常代码块: try-except
69 split() 创建单词列表
- str = 'this is a string'
- str.split()
- ['this','is','a','string']
70 存储数据 json.dump() 和 json.load()
- import json
- # 父类
- class Animal():
- def __init__(self,name,age):
- self.name = name
- self.age = age
- def animal_call(self):
- print('this is'+self.name.title()+'call.')
- # 子类
- class Cat(Animal):
- def __init__(self,name,age,color):
- super().__init__(name,age)
- self.color =color
- def cat_color(self):
- my_color = 'the cat is'+self.color
- print(my_color)
- return my_color
- if __name__ == '__main__':
- cat = Cat('tom',22,'blue')
- cat.animal_call()
- strs=cat.cat_color()
- filename = r'../AllProject/V4.0EngInfoExtract/Document/EnPapers_single/test.json'
- with open(filename,'w') as f_obj:
- json.dump(strs,f_obj)
- with open(filename,'r') as f_obj:
- strs = json.load(f_obj)
- print(strs)
来源: https://www.cnblogs.com/baiboy/p/pythonnotes1.html