python技巧(一)

来源:互联网 发布:男主是人工智能的小说 编辑:程序博客网 时间:2024/05/22 11:39

1.参数unpack

*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个 dict。并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前。

如此可以简单的给函数传递列表和字典

def draw_point(x, y):    # do some magicpoint_foo = (3, 4)point_bar = {'y': 3, 'x': 2}draw_point(*point_foo)draw_point(**point_bar)

2.枚举器

当你在迭代容器,并且需要索引时:
>>> a = ['a', 'b', 'c', 'd', 'e']>>> for index, item in enumerate(a): print index, item...0 a1 b2 c3 d4 e>>>

3.for/else

语法糖,但能是逻辑更清晰
for i in foo:    if i == 0:        breakelse:    print("i was never 0")
相比原始写法
found = Falsefor i in foo:    if i == 0:        found = True        breakif not found:     print("i was never 0")

4.新型格式化

可读性更好,不容易对错位置
found = False>>> print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42}The answer is 42.>>> foo, bar = 'question', 123>>> print "The %(foo)s is %(bar)i." % locals()The question is 123.

5.使用site-package中的.pth

增加或使用第三方哭,或对其版本配置时,使用PATHPATH环境变量不太方便可以修改site-package中的.pth

"The most convenient way [to modify python's search path] is to add a path configuration file to a directory that's already on Python's path, usually to the .../site-packages/ directory. Path configuration files have an extension of .pth, and each line must contain a single path that will be appended to sys.path. (Because the new paths are appended to sys.path, modules in the added directories will not override standard modules. This means you can't use this mechanism for installing fixed versions of standard modules.)"

6.dict的get函数

使用dict时,如果key不存在,会得到一个异常,使用dict的get函数获取一个key的value,可以对get指定一个值,这样你使用的key不在dict,你会得到默认值

7.两个值交换

python中可以不使用中间值
>>> a = 10>>> b = 5>>> a, b(10, 5)>>> a, b = b, a>>> a, b(5, 10)

8.doctest

单元测试写到注释中

def factorial(n):    """Return the factorial of n, an exact integer >= 0.    If the result is small enough to fit in an int, return an int.    Else return a long.    >>> [factorial(n) for n in range(6)]    [1, 1, 2, 6, 24, 120]    >>> factorial(-1)    Traceback (most recent call last):        ...    ValueError: n must be >= 0    Factorials of floats are OK, but the float must be an exact integer:    """    import math    if not n >= 0:        raise ValueError("n must be >= 0")    if math.floor(n) != n:        raise ValueError("n must be exact integer")    if n+1 == n:  # catch a value like 1e300        raise OverflowError("n too large")    result = 1    factor = 2    while factor <= n:        result *= factor        factor += 1    return resultdef _test():    import doctest    doctest.testmod()    if __name__ == "__main__":    _test()

9.list切块

a = [1,2,3,4,5]>>> a[::2]  # iterate over the whole list in 2-increments[1,3,5]
>>> a[::-1][5,4,3,2,1]

10.三元运算

x = 3 if (y == 1) else 2 if (y == -1) else 1
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 法院拍卖款分配有疑意怎么办 法院拍卖买到的房子里有户口怎么办 新注册手机邮箱不和电脑同步怎么办 移动4g盒当月流量封顶怎么办 昆仑加油卡密码忘记了怎么办 昆仑银行e盾密码忘记了怎么办 中石化加油卡密码忘记了怎么办 壳牌加油卡密码忘了怎么办 中国石化加油卡密码忘了怎么办 中石化加油卡密码忘了怎么办 中石化加油卡需要密码忘了怎么办 求不熟领导办事送礼不收怎么办 送礼给领导不收好像很生气怎么办 加油卡没有密码加油后锁住怎么办 个人怎么办中石化油卡怎么开公司票 中石化副卡挂失后钱怎么办 中石化的加油卡丢了怎么办 得仕卡过期3年了怎么办 如果在超市买到过期商品怎么办 华润万家买的豆干过期了吃了怎么办 华润万家购物卡过期了怎么办 杜鹃花水浇多了树叶都掉了怎么办 游客行程因天气原因无法进行怎么办 携程旅游途中提前结束行程怎么办 小区附近商家卖东西很吵怎么办? 小区门口卖东西的喇叭太吵怎么办 我老婆是二婚带的小孩怎么办户口 ck手表带了脱不下来怎么办 消毒柜开孔尺寸高度太高了怎么办 苏宁易购买的东西比专卖店贵怎么办 手机打字键盘上没有语音功能怎么办 网贷催收发语音侮辱人怎么办 康力无机房电梯到楼层不关门怎么办 档案工龄少算了工资领开了怎么办 别人骚扰我打电话报警人走了怎么办 因外借医保卡被香港保险拒保怎么办 医保和社保断了一个月怎么办 苹果8呼叫受限请勿越权使用怎么办 药物储存2~8度没冰箱怎么办 利仁分体电饼铛做饼熟的慢怎么办 闲鱼买的东西自提有问题怎么办