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

  • 2016-03-02 23:42:00
  • 1301
  • 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类

1、定义:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument. |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

2、解释:返回带计数值(从0开始)和迭代值的迭代对象,如:(0, seq[0]), (1, seq[1]), (2, seq[2]),...

​3、举例:

>>> a = range(5,10)
>>> for index, value in enumerate(a):
...     print index, value
...
0 5
1 6
2 7
3 8
4 9

二十四、eval方法

1、定义:

eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

2、解释:在全局变量、局部变量环境中运行源代码source,source可以是python表达式、或者被complie方法编译后的返回对象。

3、举例:

>>> a = '1 if True else 0'
>>> eval(a)
1
注:关于运行complie返回对象的例子可以查看讲解compile那篇:http://www.aoyanming.com/blog/display/12

 


发表评论

* *