字符串格式化
>>> "{key}={value}".format(key="a", value=10) # 使⽤命名参数'a=10'>>> "[{0:<10}], [{0:^10}], [{0:*>10}]".format("a") # 左中右对⻬'[a ], [ a ], [*********a]'>>> "{0.platform}".format(sys) # 成员'darwin'>>> "{0[a]}".format(dict(a=10, b=20)) # 字典'10'>>> "{0[5]}".format(range(10)) # 列表'5'>>> "My name is {0} :-{ {}}".format('Fred') # 真得想显示{},需要双{}'My name is Fred :-{}'>>> "{0!r:20}".format("Hello")"'Hello' ">>> "{0!s:20}".format("Hello")'Hello '>>> "Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())'Today is: Mon Mar 31 23:59:34 2014'
列表去重
>>> l = [1, 2, 2, 3, 3, 3]>>> {}.fromkeys(l).keys()[1, 2, 3] # 列表去重(1)>>> list(set(l)) # 列表去重(2)[1, 2, 3]In [2]: %timeit list(set(l))1000000 loops, best of 3: 956 ns per loopIn [3]: %timeit {}.fromkeys(l).keys()1000000 loops, best of 3: 1.1 µs per loopIn [4]: l = [random.randint(1, 50) for i in range(10000)]In [5]: %timeit list(set(l))1000 loops, best of 3: 271 µs per loopIn [6]: %timeit {}.fromkeys(l).keys()1000 loops, best of 3: 310 µs per loop PS: 在字典较大的情况下, 列表去重(1)略慢了
super 当子类调用父类属性时一般的做法是这样
>>> class LoggingDict(dict): ... def __setitem__(self, key, value):... print('Setting {0} to {1}'.format(key, value))... dict.__setitem__(self, key, value)
问题是假如你继承的不是dict而是其他,那么就要修改2处,其实可以这样
>>> class LoggingDict(dict):... def __setitem__(self, key, value):... print('Setting {0} to {1}'.format(key, value))... super(LoggingDict, self).__setitem__(key, value)
PS: 感觉super自动找到了LoggingDict的父类(dict),然后把self转化为其实例
斐波那契数列
>>> import itertools>>>>>> def fib():... a, b = 0, 1... while 1:... yield b... a, b = b, a + b...>>>>>> print list(itertools.islice(fib(), 10))[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
看到这里, 就得说说contextmanager
@contextlib.contextmanagerdef some_generator(): try: yield finally: with some_generator( ) as :
也就是:
try: = finally:
contextmanager例子(一)
>>> lock = threading.Lock()>>> @contextmanager... def openlock():... print('Acquire')... lock.acquire()... yield... print('Releasing')... lock.release()... >>> with openlock():... print('Lock is locked: {}'.format(lock.locked()))... print 'Do some stuff'... AcquireLock is locked: TrueDo some stuffReleasing
__slots__ 大量属性时减少内存占用
>>> class User(object):... __slots__ = ("name", "age")... def __init__(self, name, age):... self.name = name... self.age = age...>>> u = User("Dong", 28)>>> hasattr(u, "__dict__")False>>> u.title = "xxx"Traceback (most recent call last): File "", line 1, in AttributeError: 'User' object has no attribute 'title'
模块: itertools(一)
>>> def chunker(items, chunk_size):... for _key, group in itertools.groupby(... enumerate(items), lambda x: x[0] // chunk_size):... yield [g[1] for g in group]>>> for i in chunker(range(10), 4):... print list(i)[0, 1, 2, 3][4, 5, 6, 7][8, 9]>>> l = [(1, 10), (2, 10), (3, 20), (4, 20)]>>> for key, group in itertools.groupby(l, lambda t: t[1]):... print(key, list(group))(10, [(1, 10), (2, 10)])(20, [(3, 20), (4, 20)])