[关闭]
@nemos 2017-05-05T14:43:12.000000Z 字数 4184 阅读 812

基础语法

python


基本数据类型

集合

直接使用set内置函数即可创建集合

  1. set.xxx() #可调用未绑定版本
  2. a | b <=> a.union(b) #求并集
  3. a & b <=> a.intersection #求交集
  4. a - b <=> a.difference(b) #
  5. a ^ b <=> a.symmetric_difference(b) #
  6. a <= b <=> a.issubset(b) #判断是否为子集
  7. a >= b <=> a.isuperset(b) #判断是否为父集

不可变的版本
可使用frozenset

优先队列的一种

  1. from heapq improt *
  2. heapify(list) #将heap属性应用到列表
  3. #heap必须为通过堆函数创建的列表
  4. heappush(heap, x) #将X入堆
  5. heappop(heap) #将堆中最小元素弹出
  6. heapreplace(heap, x) #将堆中最小的元素弹出且将X入堆
  7. nlargest(n, iter) #返回iter中的n大的元素
  8. nsmammest(n, iter)

双端队列

可看成头尾相接的环状结构

  1. from collections import deuqe
  2. dq = deque(list) #创建
  3. dq.append(x)
  4. dq.appendleft(x)
  5. dq.pop()
  6. dq.popleft()
  7. dq.rotate() #左右移动,正右负左

list

  1. list[begin:end:step] #分片
  2. #分片总算返回副本
  3. newlist = list[:] #复制列表
  4. newlist = list() #转换list对象
  5. del list[1] #删除元素
  6. list[1:] = list("python") #分片赋值
  7. list[1:1] = newlist #在1位置后插入newlist
  8. list[1:4] = [] <=> del list[1:4]
  9. newlist = [None] * num #批量初始化list
  1. non = list.append(ele)
  2. num = list.count(ele) #元素出现次数
  3. non = list.extend(otherlist)
  4. num = list.index(ele) #元素第一次出现位置
  5. non = list.insert(ele, loca)
  6. ele = list.pop(loca) #默认第一个
  7. non = list.remove(ele)
  8. non = list.reverse()
  9. non = list.sort(func, key=, reverse=)

tuple

  1. 42, <=> (42,) != (42)

str

  1. "Hello,%s.%s enough for you?" % ("world", "hot") # 字符串格式化
  2. string.digits/letters/lowercase/uppercase/printable/punctuation
  3. string.ascii_letters
  4. #一些常量
  1. num = str.find(substr,begin,end) #返回最左位置,无着-1
  2. str = str.join(liststr)
  3. str = str.lower()
  4. str = str.title() #首字母大写
  5. str = str.capwords()
  6. str = str.replace(oldstr,newstr) #替换所有
  7. list = str.split(substr) #以substr分割
  8. str = str.strip() #处理字符串两侧

dict

  1. dict = dict([(key1, value1), (key2, value2)]) #通过二元元组的list构造
  2. #dic中key唯一
  3. None = dict.clear()
  4. newdict = dict.copy() #浅拷
  5. newdict = dict.deepcopu() #深拷
  6. None or value = dict.get(key,ifNone)
  7. [(key1, value1), ...] = dict.items()
  8. iterator = dict.iteritems()# keys() iterkeys()
  9. item = dict.pop(key)
  10. item = dict.popitem() #随机
  11. None = dict.setdefault() #设定默认值
  12. None = dict.update(newdict)

上下文管理

  1. import time
  2. class demo:
  3. def __init__(self, label):
  4. self.label = label
  5. def __enter__(self):
  6. self.start = time.time()
  7. def __exit__(self, exc_ty, exc_val, exc_tb):
  8. end = time.time()
  9. print('{}: {}'.format(self.label, end - self.start))
  10. with demo('counting'):
  11. n = 10000000
  12. while n > 0:
  13. n -= 1

装饰器

在函数前后添加功能

  1. def decorator_func(func):
  2. def new_func(*args, **kwargs):
  3. print('current func:', func.__name__)
  4. print('position arguments:', args)
  5. print('key arguments:', **kwargs)
  6. result = func(*args, **kwargs)
  7. print(result)
  8. return result
  9. return new_func

在装饰器中使用参数

  1. def read_file(filename='results.txt'):
  2. def decorator_fun(fun):
  3. def new_fun(*args, **kwargs):
  4. result = fun(*args, **kwargs)
  5. with open(filename, 'a') as f:
  6. f.write(result + '\n')
  7. return result
  8. return new_fun
  9. return decorator_fun
  10. # 使用装饰器时代入参数
  11. @read_file(filename='log.txt')
  12. def add(a, b):
  13. return a + b
  14. # 不会保留原函数信息
  15. print(add.__name__)
  16. # new_fun

使用wraps保留原函数信息

  1. from functools import wraps
  2. def decorator_fun(fun):
  3. @wraps(fun)
  4. def new_fun(*args, **kwargs):
  5. result = fun(*args, **kwargs)
  6. print(result)
  7. return result
  8. return new_fun
  9. @decorator_fun
  10. def add(a, b):
  11. return a + b

类封装

  1. from functools import wraps
  2. class logResult(object):
  3. def __init__(self, filename='results.txt'):
  4. self.filename = filename
  5. def __call__(self, fun):
  6. @wraps(fun)
  7. def new_fun(*args, **kwargs):
  8. result = fun(*args, **kwargs)
  9. with open(filename, 'a') as f:
  10. f.write(result + '\n')
  11. return result
  12. self.send_notification()
  13. return new_fun
  14. def send_notification(self):
  15. pass
  16. @logResult('log.txt')
  17. def add(a, b):
  18. return a + b

修饰方法

  1. class Timeit(object):
  2. def __init__(self, func):
  3. self.func = func
  4. def __call__(self, *args, **kwargs):
  5. print('invoking Timer')
  6. def __get__(self, instance, owner):
  7. return lambda *args, **kwargs: self.func(instance, *args, **kwargs)

关键字

is

  1. is #判断同一性 并不是相等
  2. 1<value<100

assert

  1. assert <=> if not condition:crash and print
  2. assert 0<age<100, 'The age is wrong'

with

  1. with EXPR as VAR:
  2. BLOCK

处理过程

  1. 计算expr获得上下文管理器
  2. 上下文管理器的exit方法被保存起来用于之后的调用
  3. 调用上下文管理器的enter方法
  4. 将EXPR的返回值值赋给VAR
  5. 执行BLOCK中的表达式
  6. 调用exit()方法,如果BLOCK发生错误则异常的type,value,sys.exc_info()将作为参数传递,否则即是三个None

异常

异常的本质是类的实例

定义

  1. class MyError(Exception):
  2. pass
  3. raise MyError('something error')
  1. raise Exception("some messsage") #抛出异常
  2. try: #捕捉区域
  3. except (err1, err2),e : #捕捉到执行
  4. #py3
  5. except err1 as e:
  6. except Exception as e:
  7. # 若空则全部捕捉
  8. else: #相当于except的分支语句
  9. finally: #不管有没有异常都会执行

生成器

包含yield关键字的函数
调用该函数返回一个生成器
每次请求一个值


函数式

基本函数

  1. filterobj = filter(func, seque) #将序列中的元素传入函数
  2. #且将返回值为真的元素组成可迭代对象
  3. mapobj = map(func, seq1, seq2, ...) #将多个序列的元素传入函数
  4. #返回迭代对象
  5. num = reduce(func, seq[, starting_value]) #累计操作

匿名函数

  1. # lambda
  2. #普通函数
  3. def add(a, b):
  4. return a + b
  5. # 匿名构造
  6. add = lambda a,b : a + b

其他

语句执行

  1. exec "print 'Hello world'" #py3中为函数
  2. #exec 直接执行语句,不会返回值
  3. eval("xxx") #对语句进行求值,并返回

常用内置函数

  1. input() # 表达式
  2. raw_input() # 原始数据
  3. #py3中 raw_input 被重置为input
  4. round() # 四舍五入
  1. globals() #返回全局变量的字典
  2. locals() #返回局部变量的字典
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注