字符串格式化
>>> "{key}={value}".format(key="a", value=10) # 使⽤命名参数
'a=10'
>>> "[{0:<10}], [{0:^10}], [{0:*>10}]".format("a") # 左中右对⻬
&#39;[a ], [ a ], [*********a]&#39;
>>> "{0.platform}".format(sys) # 成员
&#39;darwin&#39;
>>> "{0[a]}".format(dict(a&#61;10, b&#61;20)) # 字典
&#39;10&#39;
>>> "{0[5]}".format(range(10)) # 列表
&#39;5&#39;
>>> "My name is {0} :-{{}}".format(&#39;Fred&#39;) # 真得想显示{},需要双{}
&#39;My name is Fred :-{}&#39;
>>> "{0!r:20}".format("Hello")
"&#39;Hello&#39; "
>>> "{0!s:20}".format("Hello")
&#39;Hello &#39;
>>> "Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())
&#39;Today is: Mon Mar 31 23:59:34 2014&#39;
列表去重
>>> l &#61; [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 loop
In [3]: %timeit {}.fromkeys(l).keys()
1000000 loops, best of 3: 1.1 µs per loop
In [4]: l &#61; [random.randint(1, 50) for i in range(10000)]
In [5]: %timeit list(set(l))
1000 loops, best of 3: 271 µs per loop
In [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(&#39;Setting {0} to {1}&#39;.format(key, value))
... dict.__setitem__(self, key, value)
问题是假如你继承的不是dict而是其他,那么就要修改2处,其实可以这样
>>> class LoggingDict(dict):
... def __setitem__(self, key, value):
... print(&#39;Setting {0} to {1}&#39;.format(key, value))
... super(LoggingDict, self).__setitem__(key, value)
PS: 感觉super自动找到了LoggingDict的父类(dict)&#xff0c;然后把self转化为其实例
斐波那契数列
>>> import itertools
>>>
>>> def fib():
... a, b &#61; 0, 1
... while 1:
... yield b
... a, b &#61; b, a &#43; b
...
>>>
>>> print list(itertools.islice(fib(), 10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
看到这里, 就得说说contextmanager
&#64;contextlib.contextmanager
def some_generator():
try:
yield
finally:
with some_generator() as :
也就是:
try:
&#61;
finally:
contextmanager例子(一)
>>> lock &#61; threading.Lock()
>>> &#64;contextmanager
... def openlock():
... print(&#39;Acquire&#39;)
... lock.acquire()
... yield
... print(&#39;Releasing&#39;)
... lock.release()
...
>>> with openlock():
... print(&#39;Lock is locked: {}&#39;.format(lock.locked()))
... print &#39;Do some stuff&#39;
...
Acquire
Lock is locked: True
Do some stuff
Releasing
__slots__ 大量属性时减少内存占用
>>> class User(object):
... __slots__ &#61; ("name", "age")
... def __init__(self, name, age):
... self.name &#61; name
... self.age &#61; age
...
>>> u &#61; User("Dong", 28)
>>> hasattr(u, "__dict__")
False
>>> u.title &#61; "xxx"
Traceback (most recent call last):
File "", line 1, in
AttributeError: &#39;User&#39; object has no attribute &#39;title&#39;
模块: 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 &#61; [(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)])
chain: 把多个迭代器合并成一个迭代器
islice: 迭代器分片islice(func, start, end, step)