列表推导同 filter 和 map 的比较

参考廖雪峰的文档:

  • filter()函数:用于过滤序列。

filter()接收一个函数和一个序列。把传入的函数依次作用于传入的序列的每个元素,根据返回值是True还是Fasle决定保留还是丢弃该元素。

例如,忽略列表中的数字,只保留字符:

def is_char(l):
if not isinstance(l, int): # 判断传入的参数是否非整型
return l
li = [i for i in filter(is_char, ['dd', 12, 'rr!', 22, 34])]
print(li) li1 = list(filter(is_char, ['dd', 12, 'rr!', 22, 34]))
print(li1) li2 = list(filter(lambda l: not isinstance(l, int) , ['dd', 12, 'rr!', 22, 34]))
print(li2)
>>>
['dd', 'rr!']
['dd', 'rr!']
['dd', 'rr!']

廖雪峰讲解filter()函数中,有一道题是删除1-100中的素数:

# 尝试用filter删除1-100的素数
def is_not_prime(i):
if i == 1:
return True
for n in range(2, i):
if i % n == 0:
return True
return False
print(is_not_prime(2))
li3 = list(filter(is_not_prime, range(1,101)))
print(li3)
>>>
False
[1, 4, 6, 8, 9, 10, 12, ...]

可以在debug模式下运行,了解这段程序的运行过程。

  • map()函数:利用map()函数,可以把一个list转换为另一个list,所以,map()函数需要传入两个:一个方法和一个列表。

示例:参考博客

# 1.map提取字典的key
l = list(map(int, {1: 2, 2: 3, 3: 4}))
print(l)
>>>
[1, 2, 3]
# 对列表中的英文姓名进行处理,首字母大写,其他字母小写
A = ['ada', 'JOY', 'Kitty', 'LUCy', 'LouiCs', 'CIci'] def deal_name(s):
sd = s[0].upper() + s[1:].lower()
return sd B = list(map(deal_name, A))
print("转换后的名字列表: %s" %B)
print("转换前的名字列表: %s" %A)
>>>
转换后的名字列表: ['Ada', 'Joy', 'Kitty', 'Lucy', 'Louics', 'Cici']
转换前的名字列表: ['ada', 'JOY', 'Kitty', 'LUCy', 'LouiCs', 'CIci']
  • map()和filter()的组合使用
symbols = '$¢£¥€¤'
beyond_ascii = [ord(s) for s in symbols if ord(s) > 127]
print(beyond_ascii) beyond_ascii1 = list(filter(lambda c: c > 127, map(ord, symbols)))
print(beyond_ascii1)
>>>
[162, 163, 165, 8364, 164]
[162, 163, 165, 8364, 164]

最新文章

  1. 使用maven profile实现多环境可移植构建(转自CSDN)
  2. table边框美化
  3. The Four Stages of Recovering a Project
  4. MongoDB (十一) MongoDB 排序文档
  5. logback打印不出日志
  6. js模仿jquery里的几个方法parent, parentUntil, children
  7. Python - 元组(tuple) 详解 及 代码
  8. c++截取屏幕图片并保存(函数代码实现)
  9. Windows2008/2012多用户同时远程连接终端服务授权
  10. leetcode — symmetric-tree
  11. 强大而灵活的字体图标替代库iconfont
  12. Java基础(basis)-----代码块详解
  13. 异常值检测 —— MAD(median absolute deviation)
  14. mysql练习题3
  15. solr建立pdf/word/excel索引的方法
  16. hive sequencefile导入文件遇到FAILED: SemanticException Unable to load data to destination table. Error: The file that you are trying to load does not match the file format of the destination table.错误
  17. python-day43--单表查询之关键字执行优先级(重点)
  18. jps command not found已解决
  19. android 网站上下的 adt 不能显示没有安装的
  20. 团队项目(第四周之一)—GG队

热门文章

  1. 手动加入SSH支持、使用c3p0
  2. C# .NET using ManagementObjectSearcher提示缺少引用怎么办
  3. MapReduce的Reduce side Join
  4. QlikView格式化某一个单元格
  5. mybatis中批量插入数据
  6. PHP + Socket 发送http请求进而实现站点灌水
  7. Echarts 如何使用 bmap 的 API
  8. JDK和TOMCAT的安装与配置环境变量
  9. ios跟踪工具introspy使用
  10. html鼠标事件