python函数式编程,列表生成式

时间:2023-03-08 17:50:22
python函数式编程,列表生成式

1.python 中常见的集中存储数据的结构:

  列表

  集合

  字典

  元组

  字符串

  双队列

  堆

其中最常见的就是列表,字典。

2.下面讲一些运用循环获取字典列表的元素

 >>> dic={'name':'zhangsan','age':24,'city':'jinhua'}
>>> for key,value in dic.items():
print(key,value) name zhangsan
age 24
city jinhua

循环获取列表

>>> lists=[1,2,3,4,5]
>>> for item in lists:
item+1 2
3
4
5
6

3.python函数式编程的一些介绍

Python关于函数编程的一些函数有:

  map(function,list),映射函数

  filter(),过滤函数

  reduce(),规约函数

  lambda函数

  列表生成式

 >>> def inc(x):return x+1
>>> list(map(inc,lists))
[2, 3, 4, 5, 6]
将函数用lambda表达式,缩写为一行代码
>>> items=[1,2,3,4]
>>> list(map((lambda x:x+1),items))
[2, 3, 4, 5]
filter函数的使用
>>> list(filter((lambda x:x<3),items))
[1, 2]
 reduce函数需要导入reduce模块
>>> from functools import reduce
>>> reduce((lambda x,y:x/y),items)
0.041666666666666664
函数式标称的最后一个概念是列表生成式
>>> s=[x**2 for x in range(3)]
>>> s
[0, 1, 4]