六十四、reduce方法
1、定义:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.2、解释:从左到右, 累计将一个序列的所有元素以参数的形式传入到一个需要接受两个参数的方法中, 最后将这个序列逐级递减成一个值。若initial变量存在时, 则initial变量作为第一个参数加入到计算当中。
3、举例:
>>> reduce(lambda x,y: x*y, range(1,6),10) 1200 >>> reduce(lambda x,y: x*y, range(1,6)) 120 >>> reduce(lambda x,y: x*y, [], 10) 10
reload(...)
reload(module) -> module
Reload the module. The module must have been successfully imported before.>>> import sys
>>> sys.setdefaultencoding('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'setdefaultencoding'
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf8')
注:setdefaultencoding函数在被系统调用后被删除了,所以通过import引用进来时其实已经没有了,所以必须reload一次sys模块,这样setdefaultencoding才会为可用,才能在代码里修改解释器当前的字符编码。Copyright © 2021.aoyanming个人博客站
发表评论