讀代碼:
from functools import reduce
導入reduce函數
def fn(x, y):
... return x * 10 + y
...
def char2num(s):
... return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
其中s是索引號,必須是數字類型
...
reduce(fn, map(char2num, '13579'))
'13579'是字符串類型,這里可以替換為list、tuple等可迭代對象,當使用map函數時,一個個取用出的是數字類型
13579
def not_empty(s):
return s and s.strip()
and是與從句,即當s與s.strip()相等時才會為True
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
['A', 'B', 'C']
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
以上函數構造一個無窮的從3開始的奇數數列
def _not_divisible(n):
return lambda x: x % n > 0
構造一個篩選的數列
def primes():
yield 2
儲存特殊的素數2
it = _odd_iter()
初始序列
while True:
n = next(it)
返回序列的第一個數
yield n
it = filter(_not_divisible(n), it)
構造新序列,此時的it中沒有前面儲存的n,因為已經被next()取用