Python的高級特徵你知多少?
- 2019 年 10 月 4 日
- 筆記
選自:towardsdatascience
作者:George Seif
開篇先說,IEEE Spectrum 於9月6日發布了2019年最受歡迎的程式語言排名,無疑Python蟬聯第一,成績頗為亮眼。從前年開始,Python 就開始霸佔榜單長達 2 年,成為編程市場上份額最高的語言。
Python 多好用不用多說,大家看看自己用的語言就知道了。但是 Python 隱藏的高級功能你都 get 了嗎?本文中,作者列舉了 Python 中五種略高級的特徵以及它們的使用方法,快來一探究竟吧!
下面是 Python 的 5 種高級特徵,以及它們的用法。
01
Lambda 函數
Lambda 函數是一種比較小的匿名函數——匿名是指它實際上沒有函數名。
Python 函數通常使用 def a_function_name() 樣式來定義,但對於 lambda 函數,我們根本沒為它命名。這是因為 lambda 函數的功能是執行某種簡單的表達式或運算,而無需完全定義函數。
lambda 函數可以使用任意數量的參數,但表達式只能有一個。
x = lambda a, b : a * b print(x(5, 6)) # prints '30' x = lambda a : a*3 + 3 print(x(3)) # prints '12'
看它多麼簡單!我們執行了一些簡單的數學運算,而無需定義整個函數。這是 Python 的眾多特徵之一,這些特徵使它成為一種乾淨、簡單的程式語言。
02
Map 函數
Map() 是一種內置的 Python 函數,它可以將函數應用於各種數據結構中的元素,如列表或字典。對於這種運算來說,這是一種非常乾淨而且可讀的執行方式。
def square_it_func(a): return a * a x = map(square_it_func, [1, 4, 7]) print(x) # prints '[1, 16, 49]' def multiplier_func(a, b): return a * b x = map(multiplier_func, [1, 4, 7], [2, 5, 8]) print(x) # prints '[2, 20, 56]'看看上面的示例!我們可以將函數應用於單個或多個列表。實際上,你可以使用任何 Python 函數作為 map 函數的輸入,只要它與你正在操作的序列元素是兼容的。
03
Filter 函數
filter 內置函數與 map 函數非常相似,它也將函數應用於序列結構(列表、元組、字典)。二者的關鍵區別在於 filter() 將只返回應用函數返回 True 的元素。
詳情請看如下示例:
# Our numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] # Function that filters out all numbers which are odd def filter_odd_numbers(num): if num % 2 == 0: return True else: return False filtered_numbers = filter(filter_odd_numbers, numbers) print(filtered_numbers) # filtered_numbers = [2, 4, 6, 8, 10, 12, 14]
我們不僅評估了每個列表元素的 True 或 False,filter() 函數還確保只返回匹配為 True 的元素。非常便於處理檢查表達式和構建返回列表這兩步。
04
Itertools 模組
Python 的 Itertools 模組是處理迭代器的工具集合。迭代器是一種可以在 for 循環語句(包括列表、元組和字典)中使用的數據類型。
使用 Itertools 模組中的函數讓你可以執行很多迭代器操作,這些操作通常需要多行函數和複雜的列表理解。關於 Itertools 的神奇之處,請看以下示例:
from itertools import * # Easy joining of two lists into a list of tuples for i in izip([1, 2, 3], ['a', 'b', 'c']): print i # ('a', 1) # ('b', 2) # ('c', 3) # The count() function returns an interator that # produces consecutive integers, forever. This # one is great for adding indices next to your list # elements for readability and convenience for i in izip(count(1), ['Bob', 'Emily', 'Joe']): print i # (1, 'Bob') # (2, 'Emily') # (3, 'Joe') # The dropwhile() function returns an iterator that returns # all the elements of the input which come after a certain # condition becomes false for the first time. def check_for_drop(x): print 'Checking: ', x return (x > 5) for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]): print 'Result: ', i # Checking: 2 # Checking: 4 # Result: 6 # Result: 8 # Result: 10 # Result: 12 # The groupby() function is great for retrieving bunches # of iterator elements which are the same or have similar # properties a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5]) for key, value in groupby(a): print(key, value), end=' ') # (1, [1, 1, 1]) # (2, [2, 2, 2]) # (3, [3, 3]) # (4, [4]) # (5, [5])
05
Generator 函數
Generator 函數是一個類似迭代器的函數,即它也可以用在 for 循環語句中。這大大簡化了你的程式碼,而且相比簡單的 for 循環,它節省了很多記憶體。
比如,我們想把 1 到 1000 的所有數字相加,以下程式碼塊的第一部分向你展示了如何使用 for 循環來進行這一計算。
如果列表很小,比如 1000 行,計算所需的記憶體還行。但如果列表巨長,比如十億浮點數,這樣做就會出現問題了。使用這種 for 循環,記憶體中將出現大量列表,但不是每個人都有無限的 RAM 來存儲這麼多東西的。Python 中的 range() 函數也是這麼乾的,它在記憶體中構建列表。
程式碼中第二部分展示了使用 Python generator 函數對數字列表求和。generator 函數創建元素,並只在必要時將其存儲在記憶體中,即一次一個。這意味著,如果你要創建十億浮點數,你只能一次一個地把它們存儲在記憶體中!Python 2.x 中的 xrange() 函數就是使用 generator 來構建列表。
上述例子說明:如果你想為一個很大的範圍生成列表,那麼就需要使用 generator 函數。如果你的記憶體有限,比如使用移動設備或邊緣計算,使用這一方法尤其重要。
也就是說,如果你想對列表進行多次迭代,並且它足夠小,可以放進記憶體,那最好使用 for 循環或 Python 2.x 中的 range 函數。因為 generator 函數和 xrange 函數將會在你每次訪問它們時生成新的列表值,而 Python 2.x range 函數是靜態的列表,而且整數已經置於記憶體中,以便快速訪問。
# (1) Using a for loopv numbers = list() for i in range(1000): numbers.append(i+1) total = sum(numbers) # (2) Using a generator def generate_numbers(n): num, numbers = 1, [] while num < n: numbers.append(num) num += 1 return numbers total = sum(generate_numbers(1000)) # (3) range() vs xrange() total = sum(range(1000 + 1)) total = sum(xrange(1000 + 1))
任何程式語言的高級特徵通常都是通過大量的使用經驗才發現的。
這幾年,學 Python 的程式設計師的確越來越多了,甚至不少人把 Python 當作第一語言來學習。也難怪,Python 的優點太多了,它語言簡潔、開發效率高、可移植性強,並且可以和其他程式語言(比如C++)輕鬆無縫銜接。