Python 列表处理两个常用函数

需求:设计流程过程,对于列表的处理相当的多,用来提取数据,处理数据。Python 中常用的两个函数,map 和 lambda 和 reduce 对于列表的处理效率比较高。

map函数

>>>
list_x = [1,2,3,4,5,6]

>>>
def square(x):

...  return x * x

... 

>>>
r = map(square, list_x)

>>>
print(list(r))

[1, 4, 9, 16, 25, 36]

lambda函数

>>> list_x = [1,2,3,4,5]

>>> r = map(lambda x:x*x, list_x)

>>> print(list(r))

[1, 4, 9, 16, 25]

>>> list_x = [1,2,3,4,5]

>>> list_y = [2,4,6,8,10]

>>> r = map(lambda x, y:x*x + y,
list_x, list_y)

>>> print(list(r))

[3, 8, 15, 24, 35]

当两个参数数量不同时,取参数较少的为准进行计算

>>> list_x = [1,2,3,4]

>>> list_y = [2,4,6,8,10]

>>> r = map(lambda x, y:x*x + y,
list_x, list_y)

>>> print(list(r))

[3, 8, 15, 24]

reduce函数

#下面例子不是连续相加,是连续调用lambda表达式

>>> from functools import reduce

>>> list_x = [1,2,3,4,5]

>>> r = reduce(lambda x,y:x+y,
list_x)

>>> print(r)

15

>>> r = reduce(lambda x,y:x+y,
list_x, 10)#这里的10是作为初始值,作为调用lambda表达式的第一个x

25