python内置方法、模块讲解(二十三)

  • 2016-05-29 12:37:40
  • 1161
  • 0

六十四、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方法
1、定义:
reload(...)
    reload(module) -> module

    Reload the module.  The module must have been successfully imported before.
2、解释:很简单, reload一个之前已经导入过的模块
3、举例:
>>> 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才会为可用,才能在代码里修改解释器当前的字符编码。

阅读更多

python内置方法、模块讲解(二十二)

  • 2016-05-23 20:47:04
  • 1247
  • 0

六十、print方法

此方法不做多讲解,python的打印函数

六十一、property类

(以下省略)

阅读更多

python内置方法、模块讲解(二十一)

  • 2016-05-20 22:58:23
  • 1137
  • 0

五十七、open方法

​1、定义:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.

​2、解释:用file函数类型打开一个文件并返回一个文件对象。这个方法是打开一个文件的首先方法。

​3、举例:(略)

(以下省略)

阅读更多