Python常用指令
2015-11-22 01:34
609 查看
import time import os time.sleep() #延时 time.clock() #第一次调用返回程序运行的实际时间;第二次调用返回第一次调用后到这次调用的时间间隔 time.time() #当前时间戳 time.ctime() #当前时间的字符串形式 os.getcwd() #获取当前脚本路径 os.chdir('D:\\') #修改当前路径 os.linesep #当前环境下的换行分隔符 os.system('pause') #按任意键继续
执行外部.py文件
os.chdir(r'D:\test.py') exec(compile(open(r'D:\test.py').read(),r'D:\test.py','exec'))
带index的枚举
for index, item in enumerate(items): print(index, item)
字符串合并
l = ['one', 'two', 'three'] s = ''.join(l) #s='onetwothree'
字符串分割用str.split(sep=None, maxsplit=-1)
'1,2,,3,'.split(',') #输出['1', '2', '', '3', ''] ' 1 2 3 '.split() #输出['1', '2', '3'] 自动合并空格 items = 'zero one two three'.split() #方便的单词list初始化
行分割用str.splitlines([keepends])
自动舍弃空行,常用于文件操作
更复杂的要求可用re.split(pattern, string, maxsplit=0, flags=0)
显示正则表达式推导树
re.compile("^\[font(?:=(?P<size>[-+][0-9]{1,2}))?\](.*?)[/font]", re.DEBUG)
添加注释的正则表达式
pattern = """ ^ # beginning of string M{0,4} # thousands - 0 to 4 M's (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), or 500-800 (D, followed by 0 to 3 C's) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), or 50-80 (L, followed by 0 to 3 X's) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), or 5-8 (V, followed by 0 to 3 I's) $ # end of string """ re.search(pattern, 'M', re.VERBOSE)
从字符串创建对应名字的类对象
class ButtonFactory(): def create_button(self, typ): targetclass = typ.capitalize() return globals()[targetclass]()
使用方法
button_obj = ButtonFactory() button_obj.create_button('button').
线程之间队列
def worker(): while True: item = q.get() do_work(item) q.task_done() q = Queue() for i in range(num_worker_threads): t = Thread(target=worker) t.daemon = True t.start() for item in source(): q.put(item) q.join() #Queue除了提供常规的阻塞/非阻塞put() get()外,还实现了一组取决于计数的阻塞机制:每当添加元素时计数增加1,task_down()计数减1,join()阻塞直至计数归零
参数列表
def draw(x, y): # do some magic point_foo = (3, 4) point_bar = {'y': 4, 'x': 3} draw_point(*point_foo) draw_point(**point_bar) #对应参数名的字典
tuple多赋值与深度拷贝
import copy m = [1, 2, [3, 4]] a = m b = m.copy() b1, b2, b3 = m c1, c2, c3 = copy.deepcopy(m) m[1] = 20 m[2][0] = 30 print(a) print(b) print(b1, b2, b3) print(c1, c2, c3)
运行结果:
[1, 20, [30, 4]] [1, 2, [30, 4]] 1 2 [30, 4] 1 2 [3, 4]
pprint.pprint可产生相应对象的构造字符串
若更为精细地进行对象序列化,则使用Pickling
序列化
import pickle data = {'foo': [1,2,3], 'bar': ('Hello', 'world!'), 'baz': True} jar = open('data.pkl', 'wb') pickle.dump(data, jar) # 将pickle后的数据写入jar文件 jar.close()
反序列化
import pickle pkl_file = open('data.pkl', 'rb') data = pickle.load(pkl_file) print data pkl_file.close()
total = sum([num * num for num in range(1, 101)]) #lazy生成器 total = sum(num * num for num in xrange(1, 101))
集合操作
>>> a = set([1,2,3,4]) >>> b = set([3,4,5,6]) >>> a | b # Union {1, 2, 3, 4, 5, 6} >>> a & b # Intersection {3, 4} >>> a < b # Subset False >>> a - b # Difference {1, 2} >>> a ^ b # Symmetric Difference {1, 2, 5, 6}
模块结构规范
"""module docstring""" # imports # constants # exception classes # interface functions # classes # internal functions & classes def main(...): ... if __name__ == '__main__': status = main() sys.exit(status)
magic function内置函数隐含调用列表
http://www.rafekettler.com/magicmethods.html
常用:
__getattr__(self, name): self.name 当name不存在时 __setattr__(self, name, val) self.name = val 当name不存在时 __iter__(self) for x in self 迭代器 __getitem__(self, key) self[key] 下标索引访问 __setitem__(self, key, val) self[key] =val 下标索引赋值 __index__(self) x[self] 作为数组下标时
相关文章推荐
- python之路第二篇(基础篇)
- 【转】python version 2.7 required,which was not found in the registry
- Python的函数参数传递:传值?引用?
- python内置对象类型
- 我理解的python常用关键字
- python字典
- 简单解决Python文件中文编码问题
- python点滴
- leetcode Valid Parentheses python
- python集合
- 在python3.3中使用matplotlib的安装方式
- python 列表与元组
- python __new__ __init__
- 利用Python将WEBVTT格式的视频字幕文件转为SRT格式
- Python标准库urllib2的使用细节
- 机器学习实战python版第二章示例:手写识别系统
- 机器学习实战python版第三章决策树代码理解
- 初识python
- Python shutil模块
- [Python] 用Flask引入CSS无法正常显示