1.交换变量
x = 6
y = 5
x, y = y, x
print x >>> 5
print y >>> 6
2.if 语句在行内
print "Hello" if True else "World" >>> Hello
3.连接两个不同类型的对象
nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
print nfc + afc >>> ['Packers', '49ers', 'Ravens', 'Patriots']
print str(1) + " world" >>> 1 world
print `1` + "world" >>> 1 world
print 1, "world" >>> 1 world
print nfc, 1 >>> ['Packers', '49ers'] 1
4.计算技巧
# 向下取整 print 5.0//2 >>> 2
# 2的5次方 print 2**5 >>> 32
# 注意浮点数的除法
print .3/.1 >>> 3.0
print .3//.1 >>> 2.0
5.数值比较
x = 2 if 3 > x > 1: print x >>> 2
x = 2 if 1 < x > 0: print x >>> 2
6.两个列表同时迭代
nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
print teama + " vs. " + teamb
输出结果:
>>> Packers vs. Ravens
>>> 49ers vs. Patriots
7.带索引的列表迭代
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
print index, team
输出结果:
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots
8.列表推导
已知一个列表,筛选出偶数列表方法:
numbers = [1,2,3,4,5,6]
even = []
for number in numbers: if number%2 == 0:
even.append(number)
用下面的代替
numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]
9.字典推导
teams = ["Packers", "49ers", "Ravens", "Patriots"]
print {key: value for value, key in enumerate(teams)}
>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}
10.初始化列表的值
items = [0]*3
print items >>> [0,0,0]
11.将列表转换成字符串
teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams) >>> 'Packers, 49ers, Ravens, Patriots'
12.从字典中获取元素
# 不要用下列的方式:
data = {'user': 1, 'name': 'Max', 'three': 4}
try:
is_admin = data['admin']
except KeyError:
is_admin = False
# 替换为:
data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)
13.获取子列表
x = [1,2,3,4,5,6]
# 前3个 print x[:3] >>> [1,2,3]
# 中间4个 print x[1:5] >>> [2,3,4,5]
# 最后3个 print x[-3:] >>> [4,5,6]
# 奇数项 print x[::2] >>> [1,3,5]
# 偶数项 print x[1::2] >>> [2,4,6]
14.好用的工具类
# 集合(Counter库)
from collections import Counter
print Counter("hello") >>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
# 迭代工具(collections库和itertools库)
from itertools import combinations teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
print game
输出结果:
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')
补充:
装饰器(decorator):在代码运行期间动态增加功能的方式
1.不仅会运行now()函数本身,还会在每次运行now()函数前打印日志
# 定义一个能打印日志的decorator,作为一个decorator,它接受一个函数作为参数,并返回一个函数
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
#借助Python的@语法,把decorator置于函数的定义处。@log=》print_now = log(print_now)
@log
def print_now():
print('2017-10-27')
#输出结果
>>> print_now()
call print_now():
2017-10-27
由于log()是一个decorator,返回一个函数,所以,原来的print_now()函数仍然存在,只是现在同名的print_now变量指向了新的函数,于是调用print_now()将执行新函数,即在log()函数中返回的wrapper()函数。
2.根据第一点的要求再加个要求:自定义log的文本
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
# decorator用法如下:@log('execute') =》print_now = log('execute')(print_now)
@log('execute')
def print_now():
print('2017-10-27')
# 执行结果:
>>> print_now()
execute print_now():
2017-10-27
但是,还有改善的地方:当我们在print_now()函数打印函数的名字时,返回的函数名字就是'wrapper',所以,需要把原始函数的__name__等属性复制到wrapper()函数中,否则,有些依赖函数签名的代码执行就会出错。这样我们只需要在定义wrapper()的前面加上@functools.wraps(func)即可。
一个完整的decorator的写法如下:
网友评论