1. 程式人生 > >Python解包參數列表及 Lambda 表達式

Python解包參數列表及 Lambda 表達式

sed ack html () edi htm 一個 The lambda表達式

解包參數列表

當參數已經在python列表或元組中但需要為需要單獨位置參數的函數調用解包時,會發生相反的情況。例如,內置的 range() 函數需要單獨的 startstop 參數。如果它們不能單獨使用,請使用 * 運算符編寫函數調用以從列表或元組中解包參數:

>>>
>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

以同樣的方式,字典可以使用 ** 運算符來提供關鍵字參數:

>>>
>>> def parrot(voltage, state=‘a stiff‘, action=‘voom‘):
...     print("-- This parrot wouldn‘t", action, end=‘ ‘)
...     print("if you put", voltage, "volts through it.", end=‘ ‘)
...     print("E‘s", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin‘ demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn‘t VOOM if you put four million volts through it. E‘s bleedin‘ demised !

Lambda 表達式

可以用 lambda 關鍵字來創建一個小的匿名函數。這個函數返回兩個參數的和: lambda a, b: a+b 。python Lambda函數可以在需要函數對象的任何地方使用。它們在語法上限於單個表達式。從語義上來說,它們只是正常函數定義的語法糖。與嵌套函數定義一樣,lambda函數可以引用包含範圍的變量:

>>>
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

上面的例子使用一個lambda表達式來返回一個函數。另一個用法是傳遞一個小函數作為參數:

>>>
>>> pairs = [(1, ‘one‘), (2, ‘two‘), (3, ‘three‘), (4, ‘four‘)]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, ‘four‘), (1, ‘one‘), (3, ‘three‘), (2, ‘two‘)]

Python解包參數列表及 Lambda 表達式