讀代碼:
from functools import reduce導入reduce函數(shù)
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是索引號,必須是數(shù)字類型
...
reduce(fn, map(char2num, '13579'))
'13579'是字符串類型,這里可以替換為list、tuple等可迭代對象,當使用map函數(shù)時,一個個取用出的是數(shù)字類型
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
以上函數(shù)構造一個無窮的從3開始的奇數(shù)數(shù)列
def _not_divisible(n):
return lambda x: x % n > 0
構造一個篩選的數(shù)列
def primes():
yield 2 儲存特殊的素數(shù)2
it = _odd_iter() 初始序列
while True:
n = next(it) 返回序列的第一個數(shù)
yield n
it = filter(_not_divisible(n), it) 構造新序列,此時的it中沒有前面儲存的n,因為已經(jīng)被next()取用