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

  • 2016-03-04 23:37:06
  • 1137
  • 0

二十八、filter方法

1、定义:

filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.

2、解释:​返回sequence中满足function条件的item,如果不存在function,则返回sequence中本身为true的item。如果sequence为元组或者字符串,则返回的数据类型与sequence类型一致,否则返回列表

3、举例:

>>> filter(None,range(5))
[1, 2, 3, 4]
>>> filter(str.isdigit, 'fd23ew5 rt4')
'2354'
此法可以从字符串中找出所有的数字
>>> filter(str.isalpha, 'fd23ew5 rt4')
'fdewrt'
此法可以从字符串中找出所有的字母
>>> filter(None, 'fd23ew5 rt4')
'fd23ew5 rt4'
注:从上面可以看出,当function为None时,sequence为字符串和列表处理方式是不一样。

二十九、float方法

(以下省略)

阅读更多

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

  • 2016-03-04 23:16:07
  • 1072
  • 0

二十五、execfile方法

1、定义:

execfile(...)
    execfile(filename[, globals[, locals]])

    Read and execute a Python script from a file.
    The globals and locals are dictionaries, defaulting to the current
    globals and locals.  If only globals is given, locals defaults to it.

2、解释:从一个文件中读取并执行一个python脚本,默认取当前的全局变量和局部变量

3、举例:(略)

(以下省略)

阅读更多

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

  • 2016-03-02 23:42:00
  • 1122
  • 0

二十二、divmod方法

1、定义:

divmod(...)
    divmod(x, y) -> (quotient, remainder)

    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.

2、解释:以元组的形式返回x除以y的商和余数

3、举例:

>>> divmod(5,2)
(2, 1)
>>> divmod(5,0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> divmod(0,5)
(0, 0)

二十三、enumerate类

(以下省略)

阅读更多