3 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個贊
一些著名的API不再返回列表:
[...]
移除
reduce()
..使用 如果您真的需要它,但是99%的時間是顯式的
for
循環(huán)更易讀。 [...]

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個贊
的功能map和filter被有意更改為返回迭代器,并從內(nèi)置并放置在functools.reduce.
所以,為了filter和map,你可以用list()像你以前一樣看到結(jié)果。
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> import functools
>>> def add(x,y): return x+y
...
>>> functools.reduce(add, range(1, 11))
55
>>>
現(xiàn)在的建議是用生成器、表達(dá)式或列表理解替換對map和Filter的使用。例子:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> [i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> [cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>
他們說循環(huán)是99%的時間容易讀比減少,但我只堅持functools.reduce.

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個贊
reduce
from contextlib import contextmanager @contextmanagerdef noiters(*funcs): if not funcs: funcs = [map, filter, zip] # etc from functools import reduce globals()[reduce.__name__] = reduce for func in funcs: globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar)) try: yield finally: del globals()[reduce.__name__] for func in funcs: globals()[func.__name__] = func
with noiters(map): from operator import add print(reduce(add, range(1, 20))) print(map(int, ['1', '2']))
190[1, 2]
添加回答
舉報