加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

收藏,Python开发中有哪些高级技巧?

发布时间:2019-03-02 06:20:53 所属栏目:优化 来源:刘志军
导读:Python 开发中有哪些高级技巧?这是知乎上一个问题,我总结了一些常见的技巧在这里,可能谈不上多高级,但掌握这些至少可以让你的代码看起来 Pythonic 一点。如果你还在按照类C语言的那套风格来写的话,在 code review 恐怕会要被吐槽了。 列表推导式 chars

in 代替 or

  1. >>> if x == 1 or x == 2 or x == 3: 
  2. ...     pass 
  3. ... 
  4. >>> if x in (1,2,3): 
  5. ...     pass 

字典代替多个if else

  1. def fun(x): 
  2.     if x == 'a': 
  3.         return 1 
  4.     elif x == 'b': 
  5.         return 2 
  6.     else: 
  7.         return None 
  8.  
  9. def fun(x): 
  10.     return {"a": 1, "b": 2}.get(x) 

有下标索引的枚举

  1. >>> for i, e in enumerate(["a","b","c"]): 
  2. ...     print(i, e) 
  3. ... 
  4. 0 a 
  5. 1 b 
  6. 2 c 

生成器

注意区分列表推导式,生成器效率更高

  1. >>> g = (i**2 for i in range(5)) 
  2. >>> g 
  3. <generator object <genexpr> at 0x10881e518> 
  4. >>> for i in g: 
  5. ...     print(i) 
  6. ... 
  7. 16 

默认字典 defaultdict

  1. >>> d = dict() 
  2. >>> d['nums'] 
  3. KeyError: 'nums' 
  4. >>> 
  5.  
  6. >>> from collections import defaultdict 
  7. >>> d = defaultdict(list) 
  8. >>> d["nums"] 
  9. [] 

字符串格式化

  1. >>> lang = 'python' 
  2. >>> f'{lang} is most popular language in the world' 
  3. 'python is most popular language in the world' 

列表中出现次数最多的元素

  1. >>> nums = [1,2,3,3] 
  2. >>> max(set(nums), key=nums.count) 
  3.  
  4. 或者 
  5. from collections import Counter 
  6. >>> Counter(nums).most_common()[0][0] 

读写文件

  1. >>> with open("test.txt", "w") as f: 
  2. ...     f.writelines("hello") 

判断对象类型,可指定多个类型

  1. >>> isinstance(a, (int, str)) 
  2. True 

类似的还有字符串的 startswith,endswith

  1. >>> "http://foofish.net".startswith(('http','https')) 
  2. True 
  3. >>> "https://foofish.net".startswith(('http','https')) 
  4. True 

__str__ 与 __repr__ 区别

  1. >>> str(datetime.now()) 
  2. '2018-11-20 00:31:54.839605' 
  3. >>> repr(datetime.now()) 
  4. 'datetime.datetime(2018, 11, 20, 0, 32, 0, 579521)' 

前者对人友好,可读性更强,,后者对计算机友好,支持 obj == eval(repr(obj))

使用装饰器

  1. def makebold(f): 
  2. return lambda: "<b>" + f() + "</b>" 
  3.  
  4. def makeitalic(f): 
  5. return lambda: "<i>" + f() + "</i>" 
  6.  
  7. @makebold 
  8. @makeitalic 
  9. def say(): 
  10. return "Hello" 
  11.  
  12. >>> say() 
  13. <b><i>Hello</i></b> 

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读