python 基礎知識

 

字符串格式化

>>> "{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 loop
In [3]: %timeit {}.fromkeys(l).keys()
1000000 loops, best of 3: 1.1 µs per loop
In [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 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('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.contextmanager
def some_generator(<arguments>):
    <setup>
    try:
        yield <value>
    finally:
        <cleanup>
with some_generator(<arguments>) as <variable>:
    <body>

也就是:dom

<setup>
    try:
        <variable> = <value>
        <body>
    finally:
        <cleanup>

 

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'
... 
Acquire
Lock is locked: True
Do some stuff
Releasing

__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 "<stdin>", line 1, in <module>
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)])

chain: 把多個迭代器合併成一個迭代器

islice: 迭代器分片islice(func, start, end, step)

相關文章
相關標籤/搜索