Python的進階特效是什嗎?有什麼用呢?史上最全的教程!

來源:互聯網
上載者:User

標籤:title   compute   man   哪些   ons   common   資料   enter   use   

本篇文章重點介紹以下內容

Python語言的一些高階用法主要有以下幾個特性:

  • generators產生器用法
  • collections包常見用法
  • itertools包常見用法
  • packing/unpacking封包/解包特性
  • Decorators裝飾器
  • Context Managers上下文管理期

 

 

輸出結果

01123581321345589144233377610987

在Python中可以使用產生器運算式去迭代一個對象,產生器運算式和列表最大的差別就在於是否一次性將結果計算完成,舉例如下:

 

collections包是標準庫的一個模組,主要目的是用來擴充容器相關的資料類型,

我們通過dir查看collections包有哪些模組:

>>> import collections>>> dir(collections)[‘Callable‘, ‘Container‘, ‘Counter‘, ‘Hashable‘, ‘ItemsView‘, ‘Iterable‘, ‘Iterator‘, ‘KeysView‘, ‘Mapping‘, ‘MappingView‘, ‘MutableMapping‘, ‘MutableSequence‘, ‘MutableSet‘, ‘OrderedDict‘, ‘Sequence‘, ‘Set‘, ‘Sized‘, ‘ValuesView‘, ‘__all__‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘_abcoll‘, ‘_chain‘, ‘_class_template‘, ‘_eq‘, ‘_field_template‘, ‘_get_ident‘, ‘_heapq‘, ‘_imap‘, ‘_iskeyword‘, ‘_itemgetter‘, ‘_repeat‘, ‘_repr_template‘, ‘_starmap‘, ‘_sys‘, ‘defaultdict‘, ‘deque‘, ‘namedtuple‘]

我們以Counter為例:

from collections import Countera = Counter(‘blue‘)b = Counter(‘yellow‘)print(a)print(b)print((a + b).most_common(3))

輸出結果如下:

Counter({‘u‘: 1, ‘e‘: 1, ‘l‘: 1, ‘b‘: 1})Counter({‘l‘: 2, ‘y‘: 1, ‘e‘: 1, ‘o‘: 1, ‘w‘: 1})[(‘l‘, 3), (‘e‘, 2), (‘y‘, 1)]

另外defaultdict也是我常用的一個模組,defaultdict是dict的子類,允許我們通過Factory 方法來動態建立不存在的屬性,舉例如下:

from collections import defaultdictmy_dict = defaultdict(lambda: ‘Default Value‘)my_dict[‘a‘] = 42print(my_dict[‘a‘])print(my_dict[‘b‘])

運行結果如下:

42Default Value

在工作中我經常用defaultdict來構造一顆樹形資料結構來滿足我的常規需求,執行個體如下:

from collections import defaultdictimport jsondef tree(): """ Factory that creates a defaultdict that also uses this factory """ return defaultdict(tree)root = tree()root[‘Page‘][‘Python‘][‘defaultdict‘][‘Title‘] = ‘Using defaultdict‘root[‘Page‘][‘Python‘][‘defaultdict‘][‘Subtitle‘] = ‘Create a tree‘root[‘Page‘][‘Java‘] = Noneprint(json.dumps(root, indent=4))

運行結果如下:

{ "Page": { "Python": { "defaultdict": { "Subtitle": "Create a tree", "Title": "Using defaultdict" } }, "Java": null }}

 

輸出結果:

(1, 2)(1, 3)(1, 4)(2, 3)(2, 4)(3, 4)

另外chain模組也是常用模組之一

chain使用樣本:

from itertools import chainfor c in chain(range(3), range(12, 15)): print(c)

輸出結果如下:

012121314

另外itertools工具包裡還有很多常見的用法,這裡不再一一舉例,大家可以自行嘗試。

packing/unpacking特性

 

運行結果如下:

Call function repeat using a list of arguments:catscatscatscatsCall function repeat using a dictionary of keyword arguments:catscatscatscats

最後我們再迴歸到函數參數的例子上:

def f(*args, **kwargs): print("Arguments: ", args) print("Keyword arguments: ", kwargs)f(3, 4, 9, foo=42, bar=7)

以上代碼輸出:

Arguments: (3, 4, 9)Keyword arguments: {‘bar‘: 7, ‘foo‘: 42}

Decorators裝飾器

裝飾器這個文法糖相信使用flask或者bottle的同學應該都不陌生,使用django的也應該經常會遇到,但是大家有沒有去想過這個文法糖的應用情境呢?我簡單整理了下,大概有以下幾種裝飾器:

  • 緩衝裝飾器
  • 許可權驗證裝飾器
  • 計時裝飾器
  • 日誌裝飾器
  • 路由裝飾器
  • 異常處理裝飾器
  • 錯誤重試裝飾器

我們拿緩衝裝飾器舉例:

def cache(function): cached_values = {} # Contains already computed values def wrapping_function(*args): if args not in cached_values: # Call the function only if we haven‘t already done it for those parameters cached_values[args] = function(*args) return cached_values[args] return wrapping_function@cachedef fibonacci(n): print(‘calling fibonacci(%d)‘ % n) if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)print([fibonacci(n) for n in range(1, 9)])

以上代碼輸出:

calling fibonacci(1)calling fibonacci(2)calling fibonacci(0)calling fibonacci(3)calling fibonacci(4)calling fibonacci(5)calling fibonacci(6)calling fibonacci(7)calling fibonacci(8)[1, 1, 2, 3, 5, 8, 13, 21]

在Python3中有一個包叫做lrucache,就是用的裝飾器的文法糖進行實現。

lrucache的簡單實用如下:

from functools import lru_cache@lru_cache(maxsize=None)def fibonacci(n): print(‘calling fibonacci(%d)‘ % n) if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)print([fibonacci(n) for n in range(1, 9)])

運行結果:

calling fibonacci(1)calling fibonacci(2)calling fibonacci(0)calling fibonacci(3)calling fibonacci(4)calling fibonacci(5)calling fibonacci(6)calling fibonacci(7)calling fibonacci(8)[1, 1, 2, 3, 5, 8, 13, 21]

Context Managers上下文管理期

最後我們再看Python中的上下文管理器,這個文法糖在資源管理上有很常見的使用情境,比如上文中我用with open("file") as的用法,使用了with後就不用擔心檔案不會關閉了,在處理socket編程的時候也可以用。這個文法糖其實也不難就是兩個魔術方法的實現,enter 和 exit,一個控制入口,一個控制出口。

常規的使用with來統計一段代碼已耗用時間的例子:

from time import timeclass Timer(): def __init__(self, message): self.message = message def __enter__(self): self.start = time() return None # could return anything, to be used like this: with Timer("Message") as value: def __exit__(self, type, value, traceback): elapsed_time = (time() - self.start) * 1000 print(self.message.format(elapsed_time))with Timer("Elapsed time to compute some prime numbers: {}ms"): primes = [] for x in range(2, 500): if not any(x % p == 0 for p in primes): primes.append(x) print("Primes: {}".format(primes))

輸出結果:

Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]Elapsed time to compute some prime numbers: 1.055002212524414ms

總結

其實Python是一門特別人性化的語言,但凡在工程中經常遇到的問題,處理起來比較棘手的模式基本都有對應的比較優雅的解決方案。有些寫Java同學寫Python代碼經常看起來像是寫C,沒有一點Python語言的影子,因此簡單整理了下Python進階的一些用法,希望能夠協助一些同學。

歡迎關注我的部落格或者公眾號:https://home.cnblogs.com/u/Python1234/ Python學習交流

歡迎加入我的千人交流學習群:125240963

 

 

Python的進階特效是什嗎?有什麼用呢?史上最全的教程!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.