python 基础知识
python 基础知识
飞儿飞 发表于1年前
python 基础知识
  • 发表于 1年前
  • 阅读 5
  • 收藏 1
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

 

字符串格式化

>>> "{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>

也就是:

    <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)

共有 人打赏支持
粉丝 2
博文 47
码字总数 3370
×
飞儿飞
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: