35个有关Python的小技巧

从我开始学习python的时候,我就开始自己总结一个python小技巧的集合。后来当我什么时候在Stack Overflow或者在某个开源软件里看到一段很酷代码的时候,我就很惊讶:原来还能这么做!当时我会努力的自己尝试一下这段代码,直到我懂了它的整体思路以后,我就把这段代码加到我的集合里。这篇博客其实就是这个集合整理后一部分的公开亮相。如果你已经是个python大牛,那么基本上你应该知道这里面的大多数用法了,但我想你应该也能发现一些你不知道的新技巧。而如果你之前是一个c,c++,java的程序员,同时在学习python,或者干脆就是一个刚刚学习编程的新手,那么你应该会看到很多特别有用能让你感到惊奇的实用技巧,就像我当初一样。

每一个技巧和语言用法都会在一个个实例中展示给大家,也不需要有其他的说明。我已经尽力把每个例子弄的通俗易懂,但是因为读者对python的熟悉程度不同,仍然可能难免有一些晦涩的地方。所以如果这些例子本身无法让你读懂,至少这个例子的标题在你后面去Google搜索的时候会帮到你。

整个集合大概是按照难易程度排序,简单常见的在前面,比较少见的在最后。

1 拆箱

Python代码
  1. >>> a, b, c = 1, 2, 3  
  2. >>> a, b, c  
  3. (1, 2, 3)  
  4. >>> a, b, c = [1, 2, 3]  
  5. >>> a, b, c  
  6. (1, 2, 3)  
  7. >>> a, b, c = (2 * i + 1 for i in range(3))  
  8. >>> a, b, c  
  9. (1, 3, 5)  
  10. >>> a, (b, c), d = [1, (2, 3), 4]  
  11. >>> a  
  12. 1  
  13. >>> b  
  14. 2  
  15. >>> c  
  16. 3  
  17. >>> d  
  18. 4  

2 拆箱变量交换

Python代码
  1. >>> a, b = 1, 2  
  2. >>> a, b = b, a  
  3. >>> a, b  
  4. (2, 1)  

3 扩展拆箱(只兼容python3)

Python代码
  1. >>> a, *b, c = [1, 2, 3, 4, 5]  
  2. >>> a  
  3. 1  
  4. >>> b  
  5. [2, 3, 4]  
  6. >>> c  
  7. 5  

4 负数索引

Python代码
  1. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
  2. >>> a[-1]  
  3. 10  
  4. >>> a[-3]  
  5. 8  

5 切割列表

Python代码
  1. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
  2. >>> a[2:8]  
  3. [2, 3, 4, 5, 6, 7]  

6 负数索引切割列表

Python代码
  1. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
  2. >>> a[-4:-2]  
  3. [7, 8]  

7 指定步长切割列表

Python代码
  1. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
  2. >>> a[::2]  
  3. [0, 2, 4, 6, 8, 10]  
  4. >>> a[::3]  
  5. [0, 3, 6, 9]  
  6. >>> a[2:8:2]  
  7. [2, 4, 6]   

8 负数步长切割列表

Python代码
  1. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
  2. >>> a[::-1]  
  3. [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]  
  4. >>> a[::-2]  
  5. [10, 8, 6, 4, 2, 0]  

9 列表切割赋值

Python代码
  1. >>> a = [1, 2, 3, 4, 5]  
  2. >>> a[2:3] = [0, 0]  
  3. >>> a  
  4. [1, 2, 0, 0, 4, 5]  
  5. >>> a[1:1] = [8, 9]  
  6. >>> a  
  7. [1, 8, 9, 2, 0, 0, 4, 5]  
  8. >>> a[1:-1] = []  
  9. >>> a  
  10. [1, 5]  

10 命名列表切割方式

Python代码
  1. >>> a = [0, 1, 2, 3, 4, 5]  
  2. >>> LASTTHREE = slice(-3, None)  
  3. >>> LASTTHREE  
  4. slice(-3, None, None)  
  5. >>> a[LASTTHREE]  
  6. [3, 4, 5]  

11 列表以及迭代器的压缩和解压缩

Python代码
  1. >>> a = [1, 2, 3]  
  2. >>> b = ['a', 'b', 'c']  
  3. >>> z = zip(a, b)  
  4. >>> z  
  5. [(1, 'a'), (2, 'b'), (3, 'c')]  
  6. >>> zip(*z)  
  7. [(1, 2, 3), ('a', 'b', 'c')]  

12 列表相邻元素压缩器

Python代码
  1. >>> a = [1, 2, 3, 4, 5, 6]  
  2. >>> zip(*([iter(a)] * 2))  
  3. [(1, 2), (3, 4), (5, 6)]  
  4.    
  5. >>> group_adjacent = lambda a, k: zip(*([iter(a)] * k))  
  6. >>> group_adjacent(a, 3)  
  7. [(1, 2, 3), (4, 5, 6)]  
  8. >>> group_adjacent(a, 2)  
  9. [(1, 2), (3, 4), (5, 6)]  
  10. >>> group_adjacent(a, 1)  
  11. [(1,), (2,), (3,), (4,), (5,), (6,)]  
  12.    
  13. >>> zip(a[::2], a[1::2])  
  14. [(1, 2), (3, 4), (5, 6)]  
  15.    
  16. >>> zip(a[::3], a[1::3], a[2::3])  
  17. [(1, 2, 3), (4, 5, 6)]  
  18.    
  19. >>> group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))  
  20. >>> group_adjacent(a, 3)  
  21. [(1, 2, 3), (4, 5, 6)]  
  22. >>> group_adjacent(a, 2)  
  23. [(1, 2), (3, 4), (5, 6)]  
  24. >>> group_adjacent(a, 1)  
  25. [(1,), (2,), (3,), (4,), (5,), (6,)]  

13 在列表中用压缩器和迭代器滑动取值窗口

Python代码
  1. >>> def n_grams(a, n):  
  2. ...     z = [iter(a[i:]) for i in range(n)]  
  3. ...     return zip(*z)  
  4. ...  
  5. >>> a = [1, 2, 3, 4, 5, 6]  
  6. >>> n_grams(a, 3)  
  7. [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]  
  8. >>> n_grams(a, 2)  
  9. [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]  
  10. >>> n_grams(a, 4)  
  11. [(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]  

14 用压缩器反转字典

Python代码
  1. >>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}  
  2. >>> m.items()  
  3. [('a', 1), ('c', 3), ('b', 2), ('d', 4)]  
  4. >>> zip(m.values(), m.keys())  
  5. [(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]  
  6. >>> mi = dict(zip(m.values(), m.keys()))  
  7. >>> mi  
  8. {1: 'a', 2: 'b', 3: 'c', 4: 'd'}  

15 列表展开

Python代码
  1. >>> a = [[1, 2], [3, 4], [5, 6]]  
  2. >>> list(itertools.chain.from_iterable(a))  
  3. [1, 2, 3, 4, 5, 6]  
  4.    
  5. >>> sum(a, [])  
  6. [1, 2, 3, 4, 5, 6]  
  7.    
  8. >>> [x for l in a for x in l]  
  9. [1, 2, 3, 4, 5, 6]  
  10.    
  11. >>> a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]  
  12. >>> [x for l1 in a for l2 in l1 for x in l2]  
  13. [1, 2, 3, 4, 5, 6, 7, 8]  
  14.    
  15. >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]  
  16. >>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]  
  17. >>> flatten(a)  
  18. [1, 2, 3, 4, 5, 6, 7, 8]  

16 生成器表达式

Python代码
  1. >>> g = (x ** 2 for x in xrange(10))  
  2. >>> next(g)  
  3. 0  
  4. >>> next(g)  
  5. 1  
  6. >>> next(g)  
  7. 4  
  8. >>> next(g)  
  9. 9  
  10. >>> sum(x ** 3 for x in xrange(10))  
  11. 2025  
  12. >>> sum(x ** 3 for x in xrange(10) if x % 3 == 1)  
  13. 408  

17 字典推导

Python代码
  1. >>> m = {x: x ** 2 for x in range(5)}  
  2. >>> m  
  3. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}  
  4.    
  5. >>> m = {x: 'A' + str(x) for x in range(10)}  
  6. >>> m  
  7. {0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5: 'A5', 6: 'A6', 7: 'A7', 8: 'A8', 9: 'A9'}  

18 用字典推导反转字典

Python代码
  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'}  

19 命名元组

Python代码
  1. >>> Point = collections.namedtuple('Point', ['x', 'y'])  
  2. >>> p = Point(x=1.0, y=2.0)  
  3. >>> p  
  4. Point(x=1.0, y=2.0)  
  5. >>> p.x  
  6. 1.0  
  7. >>> p.y  
  8. 2.0  

20 继承命名元组

Python代码
  1. >>> class Point(collections.namedtuple('PointBase', ['x', 'y'])):  
  2. ...     __slots__ = ()  
  3. ...     def __add__(self, other):  
  4. ...             return Point(x=self.x + other.x, y=self.y + other.y)  
  5. ...  
  6. >>> p = Point(x=1.0, y=2.0)  
  7. >>> q = Point(x=2.0, y=3.0)  
  8. >>> p + q  
  9. Point(x=3.0, y=5.0)  

21 操作集合

Python代码
  1. >>> A = {1, 2, 3, 3}  
  2. >>> A  
  3. set([1, 2, 3])  
  4. >>> B = {3, 4, 5, 6, 7}  
  5. >>> B  
  6. set([3, 4, 5, 6, 7])  
  7. >>> A | B  
  8. set([1, 2, 3, 4, 5, 6, 7])  
  9. >>> A & B  
  10. set([3])  
  11. >>> A - B  
  12. set([1, 2])  
  13. >>> B - A  
  14. set([4, 5, 6, 7])  
  15. >>> A ^ B  
  16. set([1, 2, 4, 5, 6, 7])  
  17. >>> (A ^ B) == ((A - B) | (B - A))  
  18. True  

22 操作多重集合

Python代码
  1. >>> A = collections.Counter([1, 2, 2])  
  2. >>> B = collections.Counter([2, 2, 3])  
  3. >>> A  
  4. Counter({2: 2, 1: 1})  
  5. >>> B  
  6. Counter({2: 2, 3: 1})  
  7. >>> A | B  
  8. Counter({2: 2, 1: 1, 3: 1})  
  9. >>> A & B  
  10. Counter({2: 2})  
  11. >>> A + B  
  12. Counter({2: 4, 1: 1, 3: 1})  
  13. >>> A - B  
  14. Counter({1: 1})  
  15. >>> B - A  
  16. Counter({3: 1})  

23 统计在可迭代器中最常出现的元素

Python代码
  1. >>> A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])  
  2. >>> A  
  3. Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})  
  4. >>> A.most_common(1)  
  5. [(3, 4)]  
  6. >>> A.most_common(3)  
  7. [(3, 4), (1, 2), (2, 2)]  

24 两端都可操作的队列

Python代码
  1. >>> Q = collections.deque()  
  2. >>> Q.append(1)  
  3. >>> Q.appendleft(2)  
  4. >>> Q.extend([3, 4])  
  5. >>> Q.extendleft([5, 6])  
  6. >>> Q  
  7. deque([6, 5, 2, 1, 3, 4])  
  8. >>> Q.pop()  
  9. 4  
  10. >>> Q.popleft()  
  11. 6  
  12. >>> Q  
  13. deque([5, 2, 1, 3])  
  14. >>> Q.rotate(3)  
  15. >>> Q  
  16. deque([2, 1, 3, 5])  
  17. >>> Q.rotate(-3)  
  18. >>> Q  
  19. deque([5, 2, 1, 3])  

25 有最大长度的双端队列

Python代码
  1. >>> last_three = collections.deque(maxlen=3)  
  2. >>> for i in xrange(10):  
  3. ...     last_three.append(i)  
  4. ...     print ', '.join(str(x) for x in last_three)  
  5. ...  
  6. 0  
  7. 0, 1  
  8. 0, 1, 2  
  9. 1, 2, 3  
  10. 2, 3, 4  
  11. 3, 4, 5  
  12. 4, 5, 6  
  13. 5, 6, 7  
  14. 6, 7, 8  
  15. 7, 8, 9  

26 可排序词典

Python代码
  1. >>> m = dict((str(x), x) for x in range(10))  
  2. >>> print ', '.join(m.keys())  
  3. 1, 0, 3, 2, 5, 4, 7, 6, 9, 8  
  4. >>> m = collections.OrderedDict((str(x), x) for x in range(10))  
  5. >>> print ', '.join(m.keys())  
  6. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9  
  7. >>> m = collections.OrderedDict((str(x), x) for x in range(10, 0, -1))  
  8. >>> print ', '.join(m.keys())  
  9. 10, 9, 8, 7, 6, 5, 4, 3, 2, 1  

27 默认词典

Python代码
  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. 0  
  10. >>> m['b']  
  11. 0  
  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]'  

28 默认字典的简单树状表达

Python代码
  1. >>> import json  
  2. >>> tree = lambda: collections.defaultdict(tree)  
  3. >>> root = tree()  
  4. >>> root['menu']['id'] = 'file'  
  5. >>> root['menu']['value'] = 'File'  
  6. >>> root['menu']['menuitems']['new']['value'] = 'New'  
  7. >>> root['menu']['menuitems']['new']['onclick'] = 'new();'  
  8. >>> root['menu']['menuitems']['open']['value'] = 'Open'  
  9. >>> root['menu']['menuitems']['open']['onclick'] = 'open();'  
  10. >>> root['menu']['menuitems']['close']['value'] = 'Close'  
  11. >>> root['menu']['menuitems']['close']['onclick'] = 'close();'  
  12. >>> print json.dumps(root, sort_keys=True, indent=4, separators=(',', ': '))  
  13. {  
  14.     "menu": {  
  15.         "id": "file",  
  16.         "menuitems": {  
  17.             "close": {  
  18.                 "onclick": "close();",  
  19.                 "value": "Close"  
  20.             },  
  21.             "new": {  
  22.                 "onclick": "new();",  
  23.                 "value": "New"  
  24.             },  
  25.             "open": {  
  26.                 "onclick": "open();",  
  27.                 "value": "Open"  
  28.             }  
  29.         },  
  30.         "value": "File"  
  31.     }  
  32. }  

29 对象到唯一计数的映射

Python代码
  1. >>> import itertools, collections  
  2. >>> value_to_numeric_map = collections.defaultdict(itertools.count().next)  
  3. >>> value_to_numeric_map['a']  
  4. 0  
  5. >>> value_to_numeric_map['b']  
  6. 1  
  7. >>> value_to_numeric_map['c']  
  8. 2  
  9. >>> value_to_numeric_map['a']  
  10. 0  
  11. >>> value_to_numeric_map['b']  
  12. 1  

30 最大和最小的几个列表元素

Python代码
  1. >>> a = [random.randint(0, 100) for __ in xrange(100)]  
  2. >>> heapq.nsmallest(5, a)  
  3. [3, 3, 5, 6, 8]  
  4. >>> heapq.nlargest(5, a)  
  5. [100, 100, 99, 98, 98]  

31 两个列表的笛卡尔积

Python代码
  1. >>> for p in itertools.product([1, 2, 3], [4, 5]):  
  2. (1, 4)  
  3. (1, 5)  
  4. (2, 4)  
  5. (2, 5)  
  6. (3, 4)  
  7. (3, 5)  
  8. >>> for p in itertools.product([0, 1], repeat=4):  
  9. ...     print ''.join(str(x) for x in p)  
  10. ...  
  11. 0000  
  12. 0001  
  13. 0010  
  14. 0011  
  15. 0100  
  16. 0101  
  17. 0110  
  18. 0111  
  19. 1000  
  20. 1001  
  21. 1010  
  22. 1011  
  23. 1100  
  24. 1101  
  25. 1110  
  26. 1111  

32 列表组合和列表元素替代组合

Python代码
  1. >>> for c in itertools.combinations([1, 2, 3, 4, 5], 3):  
  2. ...     print ''.join(str(x) for x in c)  
  3. ...  
  4. 123  
  5. 124  
  6. 125  
  7. 134  
  8. 135  
  9. 145  
  10. 234  
  11. 235  
  12. 245  
  13. 345  
  14. >>> for c in itertools.combinations_with_replacement([1, 2, 3], 2):  
  15. ...     print ''.join(str(x) for x in c)  
  16. ...  
  17. 11  
  18. 12  
  19. 13  
  20. 22  
  21. 23  
  22. 33  

33 列表元素排列组合

Python代码
  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  

34 可链接迭代器

Python代码
  1. >>> a = [1, 2, 3, 4]  
  2. >>> for p in itertools.chain(itertools.combinations(a, 2), itertools.combinations(a, 3)):  
  3. ...     print p  
  4. ...  
  5. (1, 2)  
  6. (1, 3)  
  7. (1, 4)  
  8. (2, 3)  
  9. (2, 4)  
  10. (3, 4)  
  11. (1, 2, 3)  
  12. (1, 2, 4)  
  13. (1, 3, 4)  
  14. (2, 3, 4)  
  15. >>> for subset in itertools.chain.from_iterable(itertools.combinations(a, n) for n in range(len(a) + 1))  
  16. ...     print subset  
  17. ...  
  18. ()  
  19. (1,)  
  20. (2,)  
  21. (3,)  
  22. (4,)  
  23. (1, 2)  
  24. (1, 3)  
  25. (1, 4)  
  26. (2, 3)  
  27. (2, 4)  
  28. (3, 4)  
  29. (1, 2, 3)  
  30. (1, 2, 4)  
  31. (1, 3, 4)  
  32. (2, 3, 4)  
  33. (1, 2, 3, 4)  

35 根据文件指定列类聚

Python代码
  1. >>> import itertools  
  2. >>> with open('contactlenses.csv', 'r') as infile:  
  3. ...     data = [line.strip().split(',') for line in infile]  
  4. ...  
  5. >>> data = data[1:]  
  6. >>> def print_data(rows):  
  7. ...     print '\n'.join('\t'.join('{: <16}'.format(s) for s in row) for row in rows)  
  8. ...  
  9.    
  10. >>> print_data(data)  
  11. young               myope                   no                      reduced                 none  
  12. young               myope                   no                      normal                  soft  
  13. young               myope                   yes                     reduced                 none  
  14. young               myope                   yes                     normal                  hard  
  15. young               hypermetrope            no                      reduced                 none  
  16. young               hypermetrope            no                      normal                  soft  
  17. young               hypermetrope            yes                     reduced                 none  
  18. young               hypermetrope            yes                     normal                  hard  
  19. pre-presbyopic      myope                   no                      reduced                 none  
  20. pre-presbyopic      myope                   no                      normal                  soft  
  21. pre-presbyopic      myope                   yes                     reduced                 none  
  22. pre-presbyopic      myope                   yes                     normal                  hard  
  23. pre-presbyopic      hypermetrope            no                      reduced                 none  
  24. pre-presbyopic      hypermetrope            no                      normal                  soft  
  25. pre-presbyopic      hypermetrope            yes                     reduced                 none  
  26. pre-presbyopic      hypermetrope            yes                     normal                  none  
  27. presbyopic          myope                   no                      reduced                 none  
  28. presbyopic          myope                   no                      normal                  none  
  29. presbyopic          myope                   yes                     reduced                 none  
  30. presbyopic          myope                   yes                     normal                  hard  
  31. presbyopic          hypermetrope            no                      reduced                 none  
  32. presbyopic          hypermetrope            no                      normal                  soft  
  33. presbyopic          hypermetrope            yes                     reduced                 none  
  34. presbyopic          hypermetrope            yes                     normal                  none  
  35.    
  36. >>> data.sort(key=lambda r: r[-1])  
  37. >>> for value, group in itertools.groupby(data, lambda r: r[-1]):  
  38. ...     print '-----------'  
  39. ...     print 'Group: ' + value  
  40. ...     print_data(group)  
  41. ...  
  42. -----------  
  43. Group: hard  
  44. young               myope                   yes                     normal                  hard  
  45. young               hypermetrope            yes                     normal                  hard  
  46. pre-presbyopic      myope                   yes                     normal                  hard  
  47. presbyopic          myope                   yes                     normal                  hard  
  48. -----------  
  49. Group: none  
  50. young               myope                   no                      reduced                 none  
  51. young               myope                   yes                     reduced                 none  
  52. young               hypermetrope            no                      reduced                 none  
  53. young               hypermetrope            yes                     reduced                 none  
  54. pre-presbyopic      myope                   no                      reduced                 none  
  55. pre-presbyopic      myope                   yes                     reduced                 none  
  56. pre-presbyopic      hypermetrope            no                      reduced                 none  
  57. pre-presbyopic      hypermetrope            yes                     reduced                 none  
  58. pre-presbyopic      hypermetrope            yes                     normal                  none  
  59. presbyopic          myope                   no                      reduced                 none  
  60. presbyopic          myope                   no                      normal                  none  
  61. presbyopic          myope                   yes                     reduced                 none  
  62. presbyopic          hypermetrope            no                      reduced                 none  
  63. presbyopic          hypermetrope            yes                     reduced                 none  
  64. presbyopic          hypermetrope            yes                     normal                  none  
  65. -----------  
  66. Group: soft  
  67. young               myope                   no                      normal                  soft  
  68. young               hypermetrope            no                      normal                  soft  
  69. pre-presbyopic      myope                   no                      normal                  soft  
  70. pre-presbyopic      hypermetrope            no                      normal                  soft  
  71. presbyopic          hypermetrope            no                      normal         

原文链接: sahandsaba   翻译: 伯乐在线 - Kevin Sun
译文链接: http://blog.jobbole.com/63320/

  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓