PYTHON:一些函数的使用笔记

1、map内建函数

Help on built-in function map in module __builtin__:

map(...)
map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).

map接收一个函数和一个可迭代对象(如列表)作为参数,用函数处理列表的每个元素,生成并返回新的列表。

例如:map(lambda x: x+2, range(1, 5)) ——> [3, 4, 5, 6]

2、eval内建函数

Help on built-in function eval in module __builtin__:

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.

eval(str [,globals [,locals ]])函数将字符串str当成有效Python表达式来求值,并返回计算结果。

exec语句将字符串str当成有效Python代码来执行.提供给exec的代码的名称空间和exec语句的名称空间相同。

execfile(filename [,globals [,locals ]])函数可以用来执行一个文件。

例如:eval('3 + 5') ——> 8

     exec('sum = 3 + 5') ——> sum = 8

   execfile('test.py') ——> eval test

posted on 2013-03-24 20:10  四野  阅读(170)  评论(0编辑  收藏  举报