交换赋值
a,b = b,a
文件读写
使用with进行文件操作避免忘记写关闭文件导致的不良影响
with open('','r') as f:
do_sth(f)
格式化输出 str.fomart
print('{A} hit {B}'.format(A='Tom',b='Jerry'))
三目运算 A?X:Y
X if A else Y
switch...case
用字典的get方法实现C语言中的switch...case语句
def f(n):
return{
0:'hei',
1:'oh'
}.get(n,'a number')
列表理解
编程的时候时常遇到下面这种情况
res = []
for s in t:
res.append(s[0])
用列表理解简化上述代码,方括号就表示构建新的列表
[s[0] for s in t]
生成器
生成器表达式与列表理解相似
g = (x**2 for x in range(5))
sum(g)
表达式返回的结果是一个生成器对象,而不是一次把结果计算出来,它通过next方法迭代得到下一个值,也可以用for遍历所有值
for val in g:
print(val)
灵活使用集合
集合作为python的内置数据类型,向其中添加元素,检查成员都很快,它的一个重要特性是一个元素在一个集合中只出现一次,因此可以用集合来去重。
a - b # 集合减法
a <= b # a否是b的子集
更规范的注释
行注释
x # an integer
块注释
def fuction1(A,b):
''' Replace the value in A with b and save as a new list res
Args:
A: list, list to ...
b: int, a number that ...
Returns:
res: list, a new list
'''
文档注释
'''
--------------------------------
File Name: fun.py
Description: file to test
Author: zeng
Change Activity:
17.07.02 delete function1
--------------------------------
'''