Python常用指令
来源:互联网 发布:淘宝客手机源码 编辑:程序博客网 时间:2024/06/15 20:21
import timeimport ostime.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 stringM{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 magicpoint_foo = (3, 4)point_bar = {'y': 4, 'x': 3}draw_point(*point_foo)draw_point(**point_bar) #对应参数名的字典
tuple多赋值与深度拷贝
import copym = [1, 2, [3, 4]]a = mb = m.copy()b1, b2, b3 = mc1, c2, c3 = copy.deepcopy(m)m[1] = 20m[2][0] = 30print(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 pickledata = {'foo': [1,2,3], 'bar': ('Hello', 'world!'), 'baz': True}jar = open('data.pkl', 'wb')pickle.dump(data, jar) # 将pickle后的数据写入jar文件jar.close()
反序列化
import picklepkl_file = open('data.pkl', 'rb')data = pickle.load(pkl_file)print datapkl_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 # SubsetFalse>>> a - b # Difference{1, 2}>>> a ^ b # Symmetric Difference{1, 2, 5, 6}
模块结构规范
"""module docstring"""# imports# constants# exception classes# interface functions# classes# internal functions & classesdef 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] 作为数组下标时
0 0
- Python常用指令
- python常用指令
- python常用指令
- 常用Python的BIF指令
- python set集合常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- 常用指令
- mongodb和redis 的常用指令和python远程连接
- xshell-常用指令汇总 linux 常用指令
- Linux常用指令实际操作--常用指令
- javascript变量声明提升(hoisting)
- Ubuntu Server安装图形界面
- PNChart,简洁高效有动画效果的iOS图表库
- POJ 2001 Shortest Prefixes
- 多文件带参数上传及多文件文本信息上传工具类的封装
- Python常用指令
- C语言中的高精度乘法
- CallbackMappingJackson2HttpMessageConverter(jsonp请求)
- Java IO框架
- 今天开始每天记录所学 请努力前行 请默默前行 不要被自己的感动。
- vbox虚拟机的couldn't resolve host问题
- 单例模式的两种方式:饿汉模式与懒汉模式
- 这次空的好
- java.io包的总体框架图, 便于记忆!