| 
                        副标题[/!--empirenews.page--]
                           
Python 开发中有哪些高级技巧?这是知乎上一个问题,我总结了一些常见的技巧在这里,可能谈不上多高级,但掌握这些至少可以让你的代码看起来  Pythonic 一点。如果你还在按照类C语言的那套风格来写的话,在 code review 恐怕会要被吐槽了。 
列表推导式 
- >>> chars = [ c for c in 'python' ] 
 - >>> chars 
 - ['p', 'y', 't', 'h', 'o', 'n'] 
 
  
字典推导式 
- >>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 
 - >>> double_dict1 = {k:v*2 for (k,v) in dict1.items()} 
 - >>> double_dict1 
 - {'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10} 
 
  
集合推导式 
- >>> set1 = {1,2,3,4} 
 - >>> double_set = {i*2 for i in set1} 
 - >>> double_set 
 - {8, 2, 4, 6} 
 
  
合并字典 
- >>> x = {'a':1,'b':2} 
 - >>> y = {'c':3, 'd':4} 
 - >>> z = {**x, **y} 
 - >>> z 
 - {'a': 1, 'b': 2, 'c': 3, 'd': 4} 
 
  
复制列表 
- >>> nums = [1,2,3] 
 - >>> nums[::] 
 - [1, 2, 3] 
 - >>> copy_nums = nums[::] 
 - >>> copy_nums 
 - [1, 2, 3] 
 
  
反转列表 
- >>> reverse_nums = nums[::-1] 
 - >>> reverse_nums 
 - [3, 2, 1] 
 
  
PACKING / UNPACKING 
变量交换 
- >>> a,b = 1, 2 
 - >>> a ,b = b,a 
 - >>> a 
 - 2 
 - >>> b 
 - 1 
 
  
高级拆包 
- >>> a, *b = 1,2,3 
 - >>> a 
 - 1 
 - >>> b 
 - [2, 3] 
 
  
或者 
- >>> a, *b, c = 1,2,3,4,5 
 - >>> a 
 - 1 
 - >>> b 
 - [2, 3, 4] 
 - >>> c 
 - 5 
 
  
函数返回多个值(其实是自动packing成元组)然后unpacking赋值给4个变量 
- >>> def f(): 
 - ...     return 1, 2, 3, 4 
 - ... 
 - >>> a, b, c, d = f() 
 - >>> a 
 - 1 
 - >>> d 
 - 4 
 
  
列表合并成字符串 
- >>> " ".join(["I", "Love", "Python"]) 
 - 'I Love Python' 
 
  
链式比较 
- >>> if a > 2 and a < 5: 
 - ...     pass 
 - ... 
 - >>> if 2<a<5: 
 - ...     pass 
 
  
yield from 
- # 没有使用 field from 
 - def dup(n): 
 -     for i in range(n): 
 -         yield i 
 -         yield i 
 -  
 - # 使用yield from 
 - def dup(n): 
 -     for i in range(n): 
 -     yield from [i, i] 
 -  
 - for i in dup(3): 
 -     print(i) 
 -  
 - >>> 
 - 0 
 - 0 
 - 1 
 - 1 
 - 2 
 - 2 
 
  
                                                (编辑:我爱故事小小网_铜陵站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |