2-2 列表推导同 filter 和 map 的比较
2024-08-30 21:36:53
列表推导同 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]
最新文章
- 使用maven profile实现多环境可移植构建(转自CSDN)
- table边框美化
- The Four Stages of Recovering a Project
- MongoDB (十一) MongoDB 排序文档
- logback打印不出日志
- js模仿jquery里的几个方法parent, parentUntil, children
- Python - 元组(tuple) 详解 及 代码
- c++截取屏幕图片并保存(函数代码实现)
- Windows2008/2012多用户同时远程连接终端服务授权
- leetcode — symmetric-tree
- 强大而灵活的字体图标替代库iconfont
- Java基础(basis)-----代码块详解
- 异常值检测 —— MAD(median absolute deviation)
- mysql练习题3
- solr建立pdf/word/excel索引的方法
- 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.错误
- python-day43--单表查询之关键字执行优先级(重点)
- jps command not found已解决
- android 网站上下的 adt 不能显示没有安装的
- 团队项目(第四周之一)—GG队