接收兩個引數,乙個是函式,乙個是iterable
,map
將傳入的函式依次作用到序列的每個元素,並把結果作為新的iterator
返回。
map()函式能夠簡化程式設計>>> def f(x):
... return x * x
...>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
reduce()函式>>> from functools import reduce
>>> def add(x, y):
... return x + y
...>>> reduce(add, [1, 3, 5, 7, 9])
25>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...>>> def char2num(s):
... digits =
... return digits[s]
...>>> reduce(fn, map(char2num, '13579'))
13579
init是可選的,如果指定,則作為第一次迭代使用,如果沒有指定,就取seq中的第乙個元素。
利用map
和reduce
編寫乙個str2float
函式,把字串'123.456'
轉換成浮點數123.456
:
from functools import reduce
def str2float(s):
loc = s.find('.')
s1 = s.replace('.','')
num = reduce(fn, map(char2num, s1))
for n in range(len(s)-loc-1):
num = num/10.0
return num
def char2num(s):
digits =
return digits[s]
def fn(x, y):
return x * 10 + y
Python 函式的高階用法
python 中一切皆物件,我們定義的名稱僅僅是與這些物件繫結的識別符號。函式也不例外,它們也是物件,同樣可以被繫結到不同的名稱。def welcome info print info return welcome 輸出函式 welcome 的記憶體位址 f welcome 將 welcome 的記...
python高階用法 Python高階用法
python高階用法 三元表示式 x 10 y 20 print x if x y else y x 100 y 20 print x if x y else y 列表推導式和生成器 列表推導式 print i for i in range 10 print i 2 for i in range 1...
python之函式高階
概念預設引數是指函式或者方法在定義時為形參賦值,對應的形參為預設引數。預設引數是乙個引數定義時的概念,與呼叫無關 作用如果引數定義了預設引數,在呼叫方法或函式時,如果衛隊該引數進行傳值,則使用預設值作為該引數的值。語法 定義 def 函式名 形參1 值1,函式體.呼叫 函式名 實參 格式一 傳入實參...