1、函数式编程
filter,map,reduce是python函数式编程的三个典范:
filter在原有序列上调用函数返回满足条件为真的一个序列,条件由函数制定,比如:
def greater(x):
return x > 5;
def test_filter():
org = range(3,10)
print org
result = filter(greater,org)
print result
if __name__ == "__main__":
test_filter()
结果为[6,7,8,9]
map的功用在以下几个方面:
为序列的每一个元素调用function并返回一个序列,如:
def cube(x):
return x*3
def test_map():
org = [1,2,3,4,5,6,7]
result = map(cube, org)
print result
if __name__ == '__main__':
test_map()
结果为:[3, 6, 9, 12, 15, 18, 21]
reduce和filter,map不同,它返回一个单值;它先以序列的前两个元素调用function,再以返回值和第三个元素调用,依次执行下去;如果只有一个元素,就返回它;可以传入第三个参数作为初始值。如:
def add(x, y):
return x + y
def test_reduce_one():
print reduce(add, range(10, 20))
def test_reduce_two():
print reduce(add, range(10, 20), 20)
if __name__ == '__main__':
test_reduce_one()
test_reduce_two()
结果为145和165
2、函数参数传递
python中函数参数除了采用默认值外,还可以采用list和dictionary的形式传递,如:
def test_parm_fun(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of" , kind
for arg in arguments: print arg
print '-' * 40
keys = keywords.keys()
keys.sort()
for key in keys: print key, ":", keywords[key]
if __name__ == '__main__':
test_parm_fun("pen", "I have a pen", 3, client = "cs", server = "j2ee")
结果为:
-- Do you have any pen ?
-- I'm sorry, we're all out of pen
I have a pen
3
----------------------------------------
client : cs
server : j2ee
函数参数列表的分拆:
和上面有点相反,当传递的参数是一个列表而函数接受的参数却是分开的,这时你可以在参数前加一个*操作符自动把参数列表拆开,如:
>>> range(3,6)
[3,4,5]
>>> args=[3,6]
>>> range(*args)
[3,4,5]
字典分拆,在字典变量前加上**操作符,自动会把字典拆开,如:
def test_unpack_parm(voltage, state = 'a stiff', action = 'voom'):
print "-- This parrot wouldn't", action
print "if you put ", voltage, "volts through it."
print "E's", state, "!"
if __name__ == '__main__':
d = {"voltage" : "four million", "state" : "good"}
test_unpack_parm(**d)
结果为:
-- This parrot wouldn't voom
if you put four million volts through it.
E's good !
3、链表推导
链表推导式提供了一个创建链表的简单途径,无需使用map,filter以及lambda;每一个链表推导式包括在一个for语句之后的表达式,零或多个for或if语句,返回值是由for或if子句之后的表达式得到的元素组成的链表,如果要得到一个元组,必须加上一个括号。如:
>>> vec=[2,4,8]
>>> [x * 2 for x in vec]
[4,8,16]
>>> [x * 3 for x in vec if x > 3]
[12, 24]
>>> vec = [2,4,6]
>>> [ [x, x ** 2] for x in vec]
[ [2,4], [4,16], [6,36] ]
>>> [ (x, x ** 2) for x in vec]
[ (2,4), (4,16), (6,36) ]
>>> vec1 = [2,4,6]
>>> vec2 = [3,6,9]
>>> [ x * y for x in vec1 for y in vec2]
[6,12,18,12,24,36,18,36,54]
4: tuple has no method(元组没有任何方法),运行以下代码将报错