@nemos
2017-05-05T14:43:12.000000Z
字数 4184
阅读 812
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 deuqe
dq = 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位置后插入newlist
list[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/punctuation
string.ascii_letters
#一些常量
num = str.find(substr,begin,end) #返回最左位置,无着-1
str = 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 time
class demo:
def __init__(self, label):
self.label = label
def __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 = 10000000
while 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 result
return 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 result
return new_fun
return decorator_fun
# 使用装饰器时代入参数
@read_file(filename='log.txt')
def add(a, b):
return a + b
# 不会保留原函数信息
print(add.__name__)
# new_fun
使用wraps保留原函数信息
from functools import wraps
def decorator_fun(fun):
@wraps(fun)
def new_fun(*args, **kwargs):
result = fun(*args, **kwargs)
print(result)
return result
return new_fun
@decorator_fun
def add(a, b):
return a + b
类封装
from functools import wraps
class logResult(object):
def __init__(self, filename='results.txt'):
self.filename = filename
def __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 result
self.send_notification()
return new_fun
def send_notification(self):
pass
@logResult('log.txt')
def add(a, b):
return a + b
修饰方法
class Timeit(object):
def __init__(self, func):
self.func = func
def __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 print
assert 0<age<100, 'The age is wrong'
with EXPR as VAR:
BLOCK
异常的本质是类的实例
class MyError(Exception):
pass
raise MyError('something error')
raise Exception("some messsage") #抛出异常
try: #捕捉区域
except (err1, err2),e : #捕捉到执行
#py3
except 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 被重置为input
round() # 四舍五入
globals() #返回全局变量的字典
locals() #返回局部变量的字典