非常有用的Python技巧

开发 后端
今天给大家介绍一个非常有用的Python技巧,一起来看一下吧。

 函数连续调用 

  1. def add(x):  
  2.     class AddNum(int):  
  3.         def __call__(self, x): 
  4.             return AddNum(self.numerator + x) 
  5.      return AddNum(x)  
  6. print add(2)(3)(5)  
  7. # 10  
  8. print add(2)(3)(4)(5)(6)(7)  
  9. # 27  
  10. # javascript 版  
  11. var add = function(x){  
  12.     var addNum = function(x){  
  13.         return add(addNum + x);  
  14.     };  
  15.     addNum.toString = function(){  
  16.         return x;  
  17.     }  
  18.     return addNum;  
  19. add(2)(3)(5)//10  
  20. add(2)(3)(4)(5)(6)(7)//27 

默认值陷阱 

  1. >>> def evil(v=[]):  
  2. ...     v.append(1)  
  3. ...     print v 
  4. ...  
  5. >>> evil()  
  6. [1]  
  7. >>> evil()  
  8. [1, 1] 

读写csv文件 

  1. import csv  
  2. with open('data.csv', 'rb') as f:  
  3.     reader = csv.reader(f)  
  4.     for row in reader: 
  5.          print row  
  6. # 向csv文件写入  
  7. import csv  
  8. with open( 'data.csv', 'wb') as f:  
  9.     writer = csv.writer(f)  
  10.     writer.writerow(['name', 'address', 'age'])  # 单行写入  
  11.     data = [  
  12.             ( 'xiaoming ','china','10'),  
  13.             ( 'Lily', 'USA', '12')]   
  14.     writer.writerows(data)  # 多行写入 

数制转换 

  1. >>> int('1000', 2)  
  2.  
  3. >>> int('A', 16)  
  4. 10 

格式化 json 

  1. echo'{"k": "v"}' | python-m json.tool 

list 扁平化 

  1. list_ = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
  2. [k for i in list_ for k in i] #[1, 2, 3, 4, 5, 6, 7, 8, 9]  
  3. import numpy as np  
  4. print np.r_[[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
  5. import itertools  
  6. print list(itertools.chain(*[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))  
  7. sum(list_, [])  
  8. flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]  
  9. flatten(list_) 

list 合并 

  1. >>> a = [1, 3, 5, 7, 9]  
  2. >>> b = [2, 3, 4, 5, 6]  
  3. >>> c = [5, 6, 7, 8, 9]  
  4. >>> list(set().union(a, b, c))  
  5. [1, 2, 3, 4, 5, 6, 7, 8, 9] 

出现次数最多的 2 个字母 

  1. from collections import Counter  
  2. c = Counter('hello world')  
  3. print(c.most_common(2)) #[('l', 3), ('o', 2)] 

谨慎使用 

  1. eval("__import__('os').system('rm -rf /')", {}) 

置换矩阵 

  1. matrix = [[1, 2, 3],[4, 5, 6]] 
  2. res = zip( *matrix )   # res = [(1, 4), (2, 5), (3, 6)] 

列表推导 

  1. [item**2 for item in lst if item % 2]  
  2. map(lambda item: item ** 2, filter(lambda item: item % 2, lst))  
  3. >>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))  
  4. ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 

排列组合 

  1. >>> for p in itertools.permutations([1, 2, 3, 4]):  
  2. ...     print ''.join(str(x) for x in p)  
  3. ...  
  4. 1234  
  5. 1243  
  6. 1324  
  7. 1342  
  8. 1423  
  9. 1432  
  10. 2134  
  11. 2143  
  12. 2314  
  13. 2341  
  14. 2413  
  15. 2431  
  16. 3124  
  17. 3142  
  18. 3214  
  19. 3241  
  20. 3412  
  21. 3421  
  22. 4123  
  23. 4132  
  24. 4213  
  25. 4231  
  26. 4312  
  27. 4321  
  28. >>> for c in itertools.combinations([1, 2, 3, 4, 5], 3):  
  29. ...     print ''.join(str(x) for x in c)  
  30. ...  
  31. 123  
  32. 124  
  33. 125  
  34. 134  
  35. 135  
  36. 145  
  37. 234  
  38. 235  
  39. 245  
  40. 345  
  41. >>> for c in itertools.combinations_with_replacement([1, 2, 3], 2):  
  42. ...     print ''.join(str(x) for x in c)  
  43. ...  
  44. 11  
  45. 12  
  46. 13  
  47. 22  
  48. 23  
  49. 33  
  50. >>> for p in itertools.product([1, 2, 3], [4, 5]):  
  51. (1, 4)  
  52. (1, 5)  
  53. (2, 4)  
  54. (2, 5)  
  55. (3, 4)  
  56. (3, 5) 

默认字典 

  1. >>> m = dict()  
  2. >>> m['a']  
  3. Traceback (most recent call last):  
  4.   File "<stdin>", line 1, in <module>  
  5. KeyError: 'a'  
  6. >>>  
  7. >>> m = collections.defaultdict(int)  
  8. >>> m['a']  
  9.  
  10. >>> m['b']  
  11.  
  12. >>> m = collections.defaultdict(str)  
  13. >>> m['a']  
  14. ''  
  15. >>> m['b'] += 'a'  
  16. >>> m['b']  
  17. 'a'  
  18. >>> m = collections.defaultdict(lambda: '[default value]')  
  19. >>> m['a']  
  20. '[default value]'  
  21. >>> m['b']  
  22. '[default value]' 

反转字典 

  1. >>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}  
  2. >>> m  
  3. {'d': 4, 'a': 1, 'b': 2, 'c': 3}  
  4. >>> {v: k for k, v in m.items()}  
  5. {1: 'a', 2: 'b', 3: 'c', 4: 'd'}  

 

责任编辑:庞桂玉 来源: 马哥Linux运维
相关推荐

2023-02-19 15:22:22

React技巧

2009-02-09 11:20:06

Windows7Windows

2020-06-15 10:29:10

JavaScript开发 技巧

2021-10-30 18:59:15

Python

2013-06-14 14:57:09

Java基础代码

2022-06-27 19:01:04

Python应用程序数据

2010-07-30 09:07:12

PHP函数

2017-08-02 13:32:18

编程Java程序片段

2011-07-07 17:16:43

PHP

2011-04-06 14:08:14

jQuery

2009-03-24 14:23:59

PHP类库PHP开发PHP

2022-09-02 23:08:04

JavaScript技巧开发

2012-05-25 14:20:08

JavaScript

2018-08-03 10:02:05

Linux命令

2023-06-13 15:15:02

JavaScript前端编程语言

2013-11-05 10:03:22

Eclipse功能

2013-08-21 10:31:22

HTML5工具

2021-03-09 09:14:27

ES2019JavaScript开发

2013-08-12 15:00:24

LinuxLinux命令

2013-08-13 10:46:51

LinuxLinux命令
点赞
收藏

51CTO技术栈公众号