@nemos
        
        2017-05-05T14:43:12.000000Z
        字数 4184
        阅读 859
    python
直接使用set内置函数即可创建集合
set.xxx() #可调用未绑定版本a | b <=> a.union(b) #求并集a & b <=> a.intersection #求交集a - b <=> a.difference(b) #a ^ b <=> a.symmetric_difference(b) #a <= b <=> a.issubset(b) #判断是否为子集a >= b <=> a.isuperset(b) #判断是否为父集
不可变的版本 
可使用frozenset
优先队列的一种
from heapq improt *heapify(list) #将heap属性应用到列表#heap必须为通过堆函数创建的列表heappush(heap, x) #将X入堆heappop(heap) #将堆中最小元素弹出heapreplace(heap, x) #将堆中最小的元素弹出且将X入堆nlargest(n, iter) #返回iter中的n大的元素nsmammest(n, iter)
可看成头尾相接的环状结构
from collections import deuqedq = deque(list) #创建dq.append(x)dq.appendleft(x)dq.pop()dq.popleft()dq.rotate() #左右移动,正右负左
list[begin:end:step] #分片#分片总算返回副本newlist = list[:] #复制列表newlist = list() #转换list对象del list[1] #删除元素list[1:] = list("python") #分片赋值list[1:1] = newlist #在1位置后插入newlistlist[1:4] = [] <=> del list[1:4]newlist = [None] * num #批量初始化list
non = list.append(ele)num = list.count(ele) #元素出现次数non = list.extend(otherlist)num = list.index(ele) #元素第一次出现位置non = list.insert(ele, loca)ele = list.pop(loca) #默认第一个non = list.remove(ele)non = list.reverse()non = list.sort(func, key=, reverse=)
42, <=> (42,) != (42)
"Hello,%s.%s enough for you?" % ("world", "hot") # 字符串格式化string.digits/letters/lowercase/uppercase/printable/punctuationstring.ascii_letters#一些常量
num = str.find(substr,begin,end) #返回最左位置,无着-1str = str.join(liststr)str = str.lower()str = str.title() #首字母大写str = str.capwords()str = str.replace(oldstr,newstr) #替换所有list = str.split(substr) #以substr分割str = str.strip() #处理字符串两侧
dict = dict([(key1, value1), (key2, value2)]) #通过二元元组的list构造#dic中key唯一None = dict.clear()newdict = dict.copy() #浅拷newdict = dict.deepcopu() #深拷None or value = dict.get(key,ifNone)[(key1, value1), ...] = dict.items()iterator = dict.iteritems()# keys() iterkeys()item = dict.pop(key)item = dict.popitem() #随机None = dict.setdefault() #设定默认值None = dict.update(newdict)
import timeclass demo:def __init__(self, label):self.label = labeldef __enter__(self):self.start = time.time()def __exit__(self, exc_ty, exc_val, exc_tb):end = time.time()print('{}: {}'.format(self.label, end - self.start))with demo('counting'):n = 10000000while n > 0:n -= 1
在函数前后添加功能
def decorator_func(func):def new_func(*args, **kwargs):print('current func:', func.__name__)print('position arguments:', args)print('key arguments:', **kwargs)result = func(*args, **kwargs)print(result)return resultreturn new_func
在装饰器中使用参数
def read_file(filename='results.txt'):def decorator_fun(fun):def new_fun(*args, **kwargs):result = fun(*args, **kwargs)with open(filename, 'a') as f:f.write(result + '\n')return resultreturn new_funreturn decorator_fun# 使用装饰器时代入参数@read_file(filename='log.txt')def add(a, b):return a + b# 不会保留原函数信息print(add.__name__)# new_fun
使用wraps保留原函数信息
from functools import wrapsdef decorator_fun(fun):@wraps(fun)def new_fun(*args, **kwargs):result = fun(*args, **kwargs)print(result)return resultreturn new_fun@decorator_fundef add(a, b):return a + b
类封装
from functools import wrapsclass logResult(object):def __init__(self, filename='results.txt'):self.filename = filenamedef __call__(self, fun):@wraps(fun)def new_fun(*args, **kwargs):result = fun(*args, **kwargs)with open(filename, 'a') as f:f.write(result + '\n')return resultself.send_notification()return new_fundef send_notification(self):pass@logResult('log.txt')def add(a, b):return a + b
修饰方法
class Timeit(object):def __init__(self, func):self.func = funcdef __call__(self, *args, **kwargs):print('invoking Timer')def __get__(self, instance, owner):return lambda *args, **kwargs: self.func(instance, *args, **kwargs)
is #判断同一性 并不是相等1<value<100
assert <=> if not condition:crash and printassert 0<age<100, 'The age is wrong'
with EXPR as VAR:BLOCK
异常的本质是类的实例
class MyError(Exception):passraise MyError('something error')
raise Exception("some messsage") #抛出异常try: #捕捉区域except (err1, err2),e : #捕捉到执行#py3except err1 as e:except Exception as e:# 若空则全部捕捉else: #相当于except的分支语句finally: #不管有没有异常都会执行
包含yield关键字的函数 
调用该函数返回一个生成器 
每次请求一个值
filterobj = filter(func, seque) #将序列中的元素传入函数#且将返回值为真的元素组成可迭代对象mapobj = map(func, seq1, seq2, ...) #将多个序列的元素传入函数#返回迭代对象num = reduce(func, seq[, starting_value]) #累计操作
# lambda#普通函数def add(a, b):return a + b# 匿名构造add = lambda a,b : a + b
exec "print 'Hello world'" #py3中为函数#exec 直接执行语句,不会返回值eval("xxx") #对语句进行求值,并返回
input() # 表达式raw_input() # 原始数据#py3中 raw_input 被重置为inputround() # 四舍五入
globals() #返回全局变量的字典locals() #返回局部变量的字典