python3 番外篇map()和filter()的区别
map(function, iterable)和filter(function, iterable)
共同点:
都接受2个参数,函数和可迭代对象。对可迭代对象中的每个元素都应用一个函数。
不同点:
map()函数返回一个新的列表,返回对可迭代对象所有元素操作后的新值。
filter()函数也返回一个新的列表,但是只返回函数返回值为True的元素。
举例
map()
import random usd = [random.randint(1,10) for _ in range(10)] print(usd) cny = list(map(lambda x:x*2, usd)) print(cny) """ 返回值: usd [3, 6, 6, 4, 4, 8, 5, 5, 10, 2] cny [6, 12, 12, 8, 8, 16, 10, 10, 20, 4] """
import random usd = [random.randint(1,10) for _ in range(10)] print(usd) cny = list(map(lambda x:x>8, usd)) print(cny) """ 返回值: usd [5, 3, 3, 3, 6, 1, 10, 8, 4, 7] cny [False, False, False, False, False, False, True, False, False, False] """
filter()
import random usd = [random.randint(1,10) for _ in range(10)] print(usd) def change(x): return x * 2 cny = list(filter(change,usd)) print(cny) """ 返回值: usd [2, 1, 6, 4, 10, 5, 9, 10, 10, 8] cny [2, 1, 6, 4, 10, 5, 9, 10, 10, 8] """
import numpy as np import random usd = [random.randint(1,10) for _ in range(10)] print(usd) cny = list(filter(lambda x:x>8,usd)) print(cny) """ 返回值: usd [5, 10, 8, 4, 9, 7, 6, 9, 1, 4] cny [10, 9, 9] """
分类:
python30天养成计划
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!