你可能不知道的30个Python语言的特点技巧

开发 后端 前端
每个窍门或语言特性只能通过实例来验证,无需过多解释。虽然我已尽力使例子清晰,但它们中的一些仍会看起来有些复杂,这取决于你的熟悉程度。所以如果看过例子后还不清楚的话,标题能够提供足够的信息让你通过Google获取详细的内容。

1   介绍

从我开始学习Python时我就决定维护一个经常使用的“窍门”列表。不论何时当我看到一段让我觉得“酷,这样也行!”的代码时(在一个例子中、在StackOverflow、在开源码软件中,等等),我会尝试它直到理解它,然后把它添加到列表中。这篇文章是清理过列表的一部分。如果你是一个有经验的Python程序员,尽管你可能已经知道一些,但你仍能发现一些你不知道的。如果你是一个正在学习Python的C、C++或Java程序员,或者刚开始学习编程,那么你会像我一样发现它们中的很多非常有用。

 

每个窍门或语言特性只能通过实例来验证,无需过多解释。虽然我已尽力使例子清晰,但它们中的一些仍会看起来有些复杂,这取决于你的熟悉程度。所以如果看过例子后还不清楚的话,标题能够提供足够的信息让你通过Google获取详细的内容。

列表按难度排序,常用的语言特征和技巧放在前面。

1.1   分拆

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

1.2   交换变量分拆

  1. >>> a, b = 12 
  2. >>> a, b = b, a  
  3. >>> a, b  
  4. (21

1.3   拓展分拆 (Python 3下适用)

  1. >>> a, *b, c = [12345]  
  2. >>> a  
  3. 1 
  4. >>> b  
  5. [234]  
  6. >>> c  
  7. 5 

1.4   负索引

  1. >>> a = [012345678910]  
  2. >>> a[-1]  
  3. 10 
  4. >>> a[-3]  
  5. 8 

1.5   列表切片 (a[start:end])

  1. >>> a = [012345678910]  
  2. >>> a[2:8]  
  3. [234567

1.6   使用负索引的列表切片

  1. >>> a = [012345678910]  
  2. >>> a[-4:-2]  
  3. [78

1.7   带步进值的列表切片 (a[start:end:step])

  1. >>> a = [012345678910]  
  2. >>> a[::2]  
  3. [0246810]  
  4. >>> a[::3]  
  5. [0369]  
  6. >>> a[2:8:2]  
  7. [246

1.8   负步进值得列表切片

  1. >>> a = [012345678910]  
  2. >>> a[::-1]  
  3. [109876543210]  
  4. >>> a[::-2]  
  5. [1086420

1.9   列表切片赋值

  1. >>> a = [12345]  
  2. >>> a[2:3] = [00]  
  3. >>> a  
  4. [120045]  
  5. >>> a[1:1] = [89]  
  6. >>> a  
  7. [18920045]  
  8. >>> a[1:-1] = []  
  9. >>> a  
  10. [15

1.10   命名切片 (slice(start, end, step))

  1. >>> a = [012345]  
  2. >>> LASTTHREE = slice(-3None)  
  3. >>> LASTTHREE  
  4. slice(-3NoneNone)  
  5. >>> a[LASTTHREE]  
  6. [345

1.11   zip打包解包列表和倍数

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

1.12   使用zip合并相邻的列表项

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

1.13  使用zip和iterators生成滑动窗口 (n -grams) 

  1. >>> from itertools import islice  
  2. >>> def n_grams(a, n):  
  3. ...     z = (islice(a, i, Nonefor i in range(n))  
  4. ...     return zip(*z)  
  5. ...  
  6. >>> a = [123456]  
  7. >>> n_grams(a, 3)  
  8. [(123), (234), (345), (456)]  
  9. >>> n_grams(a, 2)  
  10. [(12), (23), (34), (45), (56)]  
  11. >>> n_grams(a, 4)  
  12. [(1234), (2345), (3456)] 

1.14   使用zip反转字典

  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'

1.15   摊平列表:

  1. >>> a = [[12], [34], [56]]  
  2. >>> list(itertools.chain.from_iterable(a))  
  3. [123456]  
  4.  
  5. >>> sum(a, [])  
  6. [123456]  
  7.  
  8. >>> [x for l in a for x in l]  
  9. [123456]  
  10.  
  11. >>> a = [[[12], [34]], [[56], [78]]]  
  12. >>> [x for l1 in a for l2 in l1 for x in l2]  
  13. [12345678]  
  14.  
  15. >>> a = [12, [34], [[56], [78]]]  
  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. [12345678

注意: 根据Python的文档,itertools.chain.from_iterable是***。

1.16   生成器表达式

  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(10if x % 3 == 1)  
  13. 408 

1.17   迭代字典

  1. >>> m = {x: x ** 2 for x in range(5)}  
  2. >>> m  
  3. {00112439416}  
  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'

1.18   通过迭代字典反转字典

  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'

1.19   命名序列 (collections.namedtuple)

  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 

1.20   命名列表的继承:

  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

1.21   集合及集合操作

  1. >>> A = {1233}  
  2. >>> A  
  3. set([123])  
  4. >>> B = {34567}  
  5. >>> B  
  6. set([34567])  
  7. >>> A | B  
  8. set([1234567])  
  9. >>> A & B  
  10. set([3])  
  11. >>> A - B  
  12. set([12])  
  13. >>> B - A  
  14. set([4567])  
  15. >>> A ^ B  
  16. set([124567])  
  17. >>> (A ^ B) == ((A - B) | (B - A))  
  18. True 

1.22   多重集及其操作 (collections.Counter)

  1. >>> A = collections.Counter([122])  
  2. >>> B = collections.Counter([223])  
  3. >>> A  
  4. Counter({2211})  
  5. >>> B  
  6. Counter({2231})  
  7. >>> A | B  
  8. Counter({221131})  
  9. >>> A & B  
  10. Counter({22})  
  11. >>> A + B  
  12. Counter({241131})  
  13. >>> A - B  
  14. Counter({11})  
  15. >>> B - A  
  16. Counter({31}) 

1.23   迭代中最常见的元素 (collections.Counter)

  1. >>> A = collections.Counter([112233334567])  
  2. >>> A  
  3. Counter({34122241516171})  
  4. >>> A.most_common(1)  
  5. [(34)]  
  6. >>> A.most_common(3)  
  7. [(34), (12), (22)] 

1.24   双端队列 (collections.deque)

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

#p#

1.25   有***长度的双端队列 (collections.deque)

  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. 01 
  8. 012 
  9. 123 
  10. 234 
  11. 345 
  12. 456 
  13. 567 
  14. 678 
  15. 789 

1.26   字典排序 (collections.OrderedDict)

  1. >>> m = dict((str(x), x) for x in range(10))  
  2. >>> print ', '.join(m.keys())  
  3. 1032547698 
  4. >>> m = collections.OrderedDict((str(x), x) for x in range(10))  
  5. >>> print ', '.join(m.keys())  
  6. 0123456789 
  7. >>> m = collections.OrderedDict((str(x), x) for x in range(100, -1))  
  8. >>> print ', '.join(m.keys())  
  9. 10987654321 

1.27   缺省字典 (collections.defaultdict)

  1. >>> m = dict()  
  2. >>> m['a']  
  3. Traceback (most recent call last):  
  4.   File "<stdin>", line 1in <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]' 

1.28   用缺省字典表示简单的树

  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.     }  

(到https://gist.github.com/hrldcpr/2012250查看详情)

1.29   映射对象到唯一的序列数 (collections.defaultdict)

  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 

1.30   ***最小元素 (heapq.nlargest和heapq.nsmallest)

  1. >>> a = [random.randint(0100for __ in xrange(100)]  
  2. >>> heapq.nsmallest(5, a)  
  3. [33568]  
  4. >>> heapq.nlargest(5, a)  
  5. [100100999898

1.31   笛卡尔乘积 (itertools.product)

  1. >>> for p in itertools.product([123], [45]):  
  2. (14)  
  3. (15)  
  4. (24)  
  5. (25)  
  6. (34)  
  7. (35)  
  8. >>> for p in itertools.product([01], 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 

1.32   组合的组合和置换 (itertools.combinations 和 itertools.combinations_with_replacement)

  1. >>> for c in itertools.combinations([12345], 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([123], 2):  
  15. ...     print ''.join(str(x) for x in c)  
  16. ...  
  17. 11 
  18. 12 
  19. 13 
  20. 22 
  21. 23 
  22. 33 

1.33   排序 (itertools.permutations)

  1. >>> for p in itertools.permutations([1234]):  
  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 

1.34   链接的迭代 (itertools.chain)

  1. >>> a = [1234]  
  2. >>> for p in itertools.chain(itertools.combinations(a, 2), itertools.combinations(a, 3)):  
  3. ...     print p  
  4. ...  
  5. (12)  
  6. (13)  
  7. (14)  
  8. (23)  
  9. (24)  
  10. (34)  
  11. (123)  
  12. (124)  
  13. (134)  
  14. (234)  
  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. (12)  
  24. (13)  
  25. (14)  
  26. (23)  
  27. (24)  
  28. (34)  
  29. (123)  
  30. (124)  
  31. (134)  
  32. (234)  
  33. (1234

1.35   按给定值分组行 (itertools.groupby)

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

英文原文:30 Python Language Features and Tricks You May Not Know About

译文链接:http://www.oschina.net/translate/thirty-python-language-features-and-tricks-you-may-not-know

责任编辑:林师授 来源: 中国开源社区编译
相关推荐

2021-01-05 11:22:58

Python字符串代码

2020-01-29 19:40:36

Python美好,一直在身边Line

2024-03-04 00:00:00

Kubernetes技巧API

2015-08-13 09:03:14

调试技巧

2020-11-03 09:51:04

JavaScript开发 技巧

2017-11-07 21:58:25

前端JavaScript调试技巧

2012-11-23 10:57:44

Shell

2022-09-20 11:58:27

NpmNode.js

2021-02-16 09:02:59

Python代码技巧

2023-02-27 09:20:24

绝对定位CSS

2023-01-29 09:46:47

Dialog弹窗模态

2017-02-23 19:42:55

AS Android代码

2021-02-28 08:34:14

CSS outline-off负值技巧

2016-09-05 13:14:11

2021-11-01 12:10:56

Python技巧代码

2019-11-25 14:05:47

Python装饰器数据

2021-02-21 06:36:57

运算技巧按位

2021-07-12 07:59:06

安全 HTML 属性

2022-04-30 19:22:35

Python编程语言

2009-09-04 11:06:06

Linux桌面Linux操作系统linux
点赞
收藏

51CTO技术栈公众号