博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 基础知识
阅读量:6824 次
发布时间:2019-06-26

本文共 3430 字,大约阅读时间需要 11 分钟。

hot3.png

 

字符串格式化

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

chain: 把多个迭代器合并成一个迭代器

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

转载于:https://my.oschina.net/u/2603728/blog/802173

你可能感兴趣的文章
spring boot项目开发中遇到问题,持续更新
查看>>
探索虚函数(二)
查看>>
大一秋季学期学习总结
查看>>
骄傲狮子座的感情世界(图
查看>>
李青云老人的长寿秘诀【转】
查看>>
Springboot Thymeleaf 发邮件 将html内容展示在邮件内容中
查看>>
EasyUI datagrid 行编辑
查看>>
json概述及python处理json等数据类型
查看>>
[LeetCode] Range Sum Query - Immutable
查看>>
maven遇到的一些问题
查看>>
OC-Q&A
查看>>
BZOJ2434:[NOI2011]阿狸的打字机——题解
查看>>
BZOJ - 3963: [WF2011]MachineWorks
查看>>
第5件事 做一个有taste的产品人
查看>>
暂时记录
查看>>
MicroPython开发之物联网快速开发板
查看>>
Mysql分布式部署高可用集群方案
查看>>
PHP中常用的输出语句比较?
查看>>
windows下oracleSQLDevelpment连接ORA-12560解决办法
查看>>
android&nbsp;setBackgroundColor
查看>>