博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中的map,filter,zip函数
阅读量:4345 次
发布时间:2019-06-07

本文共 1251 字,大约阅读时间需要 4 分钟。

map()

Return an iterator that applies function to every item of iterable, yielding the results

例如:

a = map(lambda x:x**2 ,[1,2,3])print([b for b in a])

结果:

[1, 4, 9]

或者:

a = map(lambda x,y:x+y ,[1,2,3],[1,2])print([b for b in a])

结果:

[2, 4]

 

filter(functioniterable)

Construct an iterator from those elements of iterable for which function returns true.If function is None, all elements of iterable that are false are removed

例子:

a = filter(lambda x:x>2, [1,2,3])print([b for b in a])

或者 function is None:

a = filter(None,[1,2,0,-1])print([b for b in a])

结果:

[1, 2, -1]

 

zip()

Make an iterator that aggregates elements from each of the iterables

例子

x = [1, 2, 3]y = [4, 5, 6]zipped = zip(x, y)zipped = list(zipped)print(zipped)

结果

[(1, 4), (2, 5), (3, 6)]

 

dict()

>>> a = dict(one=1, two=2, three=3)>>> b = {
'one': 1, 'two': 2, 'three': 3}>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))>>> d = dict([('two', 2), ('one', 1), ('three', 3)])>>> e = dict({
'three': 3, 'one': 1, 'two': 2})>>> a == b == c == d == eTrue

 

一个综合的例子

a = map(lambda x: dict(zip(['number'], [x])),filter(lambda x: x > 3, [1,2,3,4,5,6]))print([b for b in a])

结果

[{
'number': 4}, {
'number': 5}, {
'number': 6}]

 

转载于:https://www.cnblogs.com/duyang/p/5236690.html

你可能感兴趣的文章
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
Sybase IQ导出文件的几种方式
查看>>
案例:手动输入一个字符串,打散放进一个列表,小写字母反序 大写字母保持不变...
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>
阿里负载均衡,配置中间证书问题(在starcom申请免费DV ssl)
查看>>
转:How to force a wordbreaker to be used in Sharepoint Search
查看>>
MySQL存储过程定时任务
查看>>
Python中and(逻辑与)计算法则
查看>>
POJ 3267 The Cow Lexicon(动态规划)
查看>>
设计原理+设计模式
查看>>
tomcat 7服务器跨域问题解决
查看>>
前台实现ajax 需注意的地方
查看>>