随笔分类 - python
摘要:python中with可以明显改进代码友好度,比如:with open('a.txt') as f: print f.readlines() 为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:>>> class A: def __enter__(self): print 'in enter' def __exit__(self, e_t, e_v, t_b): print 'in exit' >>> with A() as a: print 'in
阅读全文
摘要:一直对itertools怀有敬畏之心,其实会了就还好了,that's nothing这里的迭代器最主要得特点就是lazy,和stl里面得迭代器还是不一样得,最明显得好处就是节省内存了。顾名思义,itertools得函数返回得都是迭代器,为简单起事,下面就不专门说明了count(p,q) 返回p, p+q, p+2*q, ....cycle(p) 返回 p[0], p[1],...p[last],p[0],p[1]......repeat(p, n) 返回 p...p (n times)chain(p,q..) 把几个参数连接起来compress(data, selectors) 比如c
阅读全文
摘要:In [6]: def return_non(): print '-----------' ...: while True: ...: print '##############' ...: x = yield ...: print x ...: print '%%%%%%%%%%%%' ...: In [8]: y = return_non() In [9]: y Out[9]: <generator object return_non at ...
阅读全文
摘要:今天学习了几个pythonku1. multiprocessimport os, time from multiprocessing import * def test(x): print current_process().pid, x time.sleep(1) if __name__ == "__main__": print "main:", os.getpid() p = Pool(5) p.map(test, range(12)) import os, time, sys, atexit from multip...
阅读全文
摘要:学习python这么久对python的metaclass还是一知半解,网上找了找,发现stackoverflow太强大了: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 这个回答很详细,太厉害了,这里自己总结一下,免的忘记。1. 类也是对象(class are object), 类在内存中也占有一段空间,所以class Foo(object):pass id(Foo) #有值 Foo.bar = 'bar' #给类添加一个属性2. 可以动态的创建类type(class_name,
阅读全文
摘要:aiomsgView more presentations orUpload your own.
阅读全文
摘要:在python中怎么一行实现循环执行语句,就像ruby中的100.times { p 'xxxxxx' }这样的语句,想了一会好像没有想法ps: 脑袋僵化了,这个其实很简单嘛for i in range(100): print 'xxxxx'
阅读全文
摘要:这里只用python来分析说明。python自带的两个cPickle, marshal我用过或尝试过的包括simplejson, AMF, protoBuf, MessagePack就这些来分析比较一下吧。import timeimport cPickleimport simplejsonimport marshalimport msgpackimport cjsontest_obj = ['abc', 123, {"abc":123}, ("abc", 123), 4.56]times = 100000st = time.clock()
阅读全文
摘要:刚看到haskell的higher order function 偏函数那一节, 想到python也有这东西, 知道但没看过,就看看大致的实现是这样的:def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*(args + fargs), **newkeywords) newfunc.func = f...
阅读全文
摘要:import random#如果剩余选择空间个数乘以随机数大于等于剩余选择数,则选择该数,否则跳过def sample(sets, n): res = [] m = t = 0 N = len(sets) for item in sets: u = random.random() if (N-t)*u >= (n-m): t += 1 else: res.append(item) m += 1 t += 1 if m >...
阅读全文
摘要:import timedef fun(x=time.time()): print 'in fun', xprint time.time()time.sleep(3)print time.time()fun()fun(time.time())print result is:1304556761.251304556764.25in fun 1304556761.25in fun 1304556764.25
阅读全文
摘要:转自:http://ipie.blogbus.com/logs/19379694.html首先要搞清楚,字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。 decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串转换成unicode编码。encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode
阅读全文

浙公网安备 33010602011771号