ITeye博客

python

共 7 篇文章

python的list和tuple

列表是python中简单而重要的数据结构 list_sample = [1, 2, 3] 超预分配的量大概只有总量的八分之一,保证不太浪费的情况下,也有线性的摊分复杂度。 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) 当增加或删除都有可能引起allocated的变化,当目前的allocated满足 allocated >= newsize && newsize >= (allocated >> 1) 这个关系时,allocated不变,不然更新分配值 allocated = new_allocated + newsize 由于p…

2013-10-12 15:06 · python

用python将html去除格式转unicode

见html中的一些奇怪的编码 http://www.w3school.com.cn/tags/html_ref_symbols.html 例如以下这么一串东西就是实体编码 小何很好啊! 如果一个html文本想把它去除html的tag,然后又把它转为系统可识别的编码(例如utf8) 以下python代码把它转为unicode,然后想转什么都可以了。 from HTMLParser import HTMLParser def strip_tags(html): html_parser = HTMLParser() # remove format #html = html.strip() #htm…

2013-07-17 17:43 · python

使用python的建议

本帖持续更新: 1、避免使用__del__ http://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour 2、在局部使用全局变量时使用global python在运行函数的时候,首先会静态地扫一遍, 把所有变量(静态、没赋予实际的值)放入局部变量列表中,导致前面的引用失败。例如 bar = 1 def foo(): print bar bar = 0 3、不要用可变的值作为参数默认值,可以用None代替 因为可变的值会在定义的时候初始化,然后就一直引用它了, 以后若这个可变的值发生…

2013-06-05 10:57 · python

python的decorator@

decorator是python的一个特性。 decorator可以是函数也可以是一个类。 decorator@的用处: 1)在函数开始前做一些初始工作,例如参数校验,调用统计等。 2)在函数结束后做一些收尾工作。 3)类似C++模板的功能。 decorator是函数时, def decorator(fun): def call(*args, **kwargs): print "do something before fun!" if len(args) < 1: print "args is less" else: fun(args[0]) print "do something afte…

2013-05-14 19:44 · python

python扫盲1

yield可以用来实现generator next()和send(msg)的返回值是yield的参数。 send(msg)的时候msg就作为对应yield返回值, 例如t = yield 22,t就为msg。 self.throw(GeneratorExit) 人工终止generator is和==的区别 python中每个对象有3个属性id、type、value is是id(对象的唯一标识,引用机制)的比较 ==是value的比较 pass 没有啥都没有,用这个是为了代码美观、统一 with obj as f: do sth. OBJ必须有__enter__和__exit__方法 然后这个…

2013-04-19 16:10 · python

python2.7打印字符串时出现UnicodeEncodeError

python在打印字符串的时候会把目标串转成unicode编码, 然后在转换成平台指定的编码例如utf-8,ascii等格式。不同版本的python有默认encode方式。 python3.2: print(sys.getdefaultencoding()) utf-8 python2.7: print sys.getdefaultencoding() ascii 如果encode的格式跟字符串原先的格式不同(或者说不兼容)就会出错。 UnicodeEncodeError: 'ascii' codec can't encode characters in position xx-yy: or…

2013-01-26 22:05 · python

python扫盲0

hello world太简单,看不出语法,写个长点的,也算对python的语法有大概的了解了,哈哈哈。 功能:root是找到没有被包含的头文件,allh是看一个源文件都包含了哪些头文件。 没啥用,当练手。 #!/usr/bin/python #python code practice for include discovery import os pre = "#include" def compact(str): #local variable assignment before referenced l = len(str) i = 0 res = "" while i < l: if …

2012-08-11 20:08 · python