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

开发 后端
Python 开发中有哪些高级技巧?这是知乎上一个问题,我总结了一些常见的技巧在这里,可能谈不上多高级,但掌握这些至少可以让你的代码看起来 Pythonic 一点。如果你还在按照类C语言的那套风格来写的话,在 code review 恐怕会要被吐槽了。

[[258483]]

Python 开发中有哪些高级技巧?这是知乎上一个问题,我总结了一些常见的技巧在这里,可能谈不上多高级,但掌握这些至少可以让你的代码看起来 Pythonic 一点。如果你还在按照类C语言的那套风格来写的话,在 code review 恐怕会要被吐槽了。

列表推导式

  1. >>> chars = [ c for c in 'python' ] 
  2. >>> chars 
  3. ['p''y''t''h''o''n'

字典推导式

 

  1. >>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 
  2. >>> double_dict1 = {k:v*2 for (k,v) in dict1.items()} 
  3. >>> double_dict1 
  4. {'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10} 

集合推导式

  1. >>> set1 = {1,2,3,4} 
  2. >>> double_set = {i*2 for i in set1} 
  3. >>> double_set 
  4. {8, 2, 4, 6} 

合并字典

 

  1. >>> x = {'a':1,'b':2} 
  2. >>> y = {'c':3, 'd':4} 
  3. >>> z = {**x, **y} 
  4. >>> z 
  5. {'a': 1, 'b': 2, 'c': 3, 'd': 4} 

复制列表

 

  1. >>> nums = [1,2,3] 
  2. >>> nums[::] 
  3. [1, 2, 3] 
  4. >>> copy_nums = nums[::] 
  5. >>> copy_nums 
  6. [1, 2, 3] 

反转列表

 

  1. >>> reverse_nums = nums[::-1] 
  2. >>> reverse_nums 
  3. [3, 2, 1] 

PACKING / UNPACKING

变量交换

 

  1. >>> a,b = 1, 2 
  2. >>> a ,b = b,a 
  3. >>> a 
  4. >>> b 

高级拆包

 

  1. >>> a, *b = 1,2,3 
  2. >>> a 
  3. >>> b 
  4. [2, 3] 

或者

 

  1. >>> a, *b, c = 1,2,3,4,5 
  2. >>> a 
  3. >>> b 
  4. [2, 3, 4] 
  5. >>> c 

函数返回多个值(其实是自动packing成元组)然后unpacking赋值给4个变量

 

  1. >>> def f(): 
  2. ...     return 1, 2, 3, 4 
  3. ... 
  4. >>> a, b, c, d = f() 
  5. >>> a 
  6. >>> d 

列表合并成字符串

 

  1. >>> " ".join(["I""Love""Python"]) 
  2. 'I Love Python' 

链式比较

  1. >>> if a > 2 and a < 5: 
  2. ...     pass 
  3. ... 
  4. >>> if 2<a<5: 
  5. ...     pass 

 

yield from

 

  1. # 没有使用 field from 
  2. def dup(n): 
  3.     for i in range(n): 
  4.         yield i 
  5.         yield i 
  6.  
  7. # 使用yield from 
  8. def dup(n): 
  9.     for i in range(n): 
  10.     yield from [i, i] 
  11.  
  12. for i in dup(3): 
  13.     print(i) 
  14.  
  15. >>> 

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> 

不使用装饰器,可读性非常差

 

  1. def say(): 
  2. return "Hello" 
  3.  
  4. >>> makebold(makeitalic(say))() 
  5. <b><i>Hello</i></b> 

 

责任编辑:庞桂玉 来源: Python爱好者社区
相关推荐

2016-11-25 13:34:42

Python开发

2022-11-30 08:17:41

JVM调优技巧

2022-09-30 10:44:47

Netty组件数据

2010-04-15 10:34:16

Oracle程序开发

2011-07-27 16:11:47

开发技巧jQuery Mobi

2020-05-28 08:59:40

Python机器学习开发

2022-11-07 16:06:15

TypeScript开发技巧

2023-05-08 15:59:17

Redis数据删除

2010-07-16 09:24:59

Perl模式

2020-07-10 06:10:14

Python开发代码

2022-11-28 08:02:17

DNSIP计算机

2020-03-13 09:29:27

物联网通信互联网

2024-01-15 17:26:26

JavaScriptWeb开发

2022-08-29 14:56:56

Python脚本代码

2013-07-22 10:01:03

JavascriptWeb

2023-11-27 13:53:00

Java数据转换

2019-07-16 14:59:00

JVM内存区域

2023-10-16 23:53:22

数据索引工具

2022-04-20 07:42:08

Python脚本代码

2022-12-10 08:15:06

点赞
收藏

51CTO技术栈公众号