你可能不知道的30個Python語言的特點技巧

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]) 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章