Python zip(), map(), filter(), reduce()

  1. zip
a = [1,2,3]
b = ['a','b','c']
c = [1,2,3]
d = ['a','b','c']
print(dict(zip(a,b))) #{1: 'a', 2: 'b', 3: 'c'}
print(list(zip(a,b))) # [(1, 'a'), (2, 'b'), (3, 'c')]
  1. filter

filter(function or None, iterable) 遍历可迭代对象,过滤符合要求的值

c = [-10, 28, 9, -5, 30, 5]
print(list(filter(lambda a:a>0, c)))
  1. map

map(function or None, iterable) 遍历可迭代对象,每个值作用到函数,返回一个列表

c = [-10, 28, 9, -5, 30, 5]
print(list(map(lambda a:a>0, c)))
  1. reduce

educe() 函数表示对参数序列中所有元素进行累积
print (reduce(lambda x,y:x+y, range(1, 101))) # 计算1-100的值
5.map和filter的却别

def only_int(x):
try:
if isinstance(x, int):
return True
else:
return False
except ValueError as e:
return False
dt1 = filter(only_int, [1, 2, 3, 3, '3232', -34.5, 34.5])
print(list(dt1)) #[1, 2, 3, 3]
dt2 = map(only_int, [1, 2, 3, 3, '3232', -34.5, 34.5])
print(list(dt2)) # [True, True, True, True, False, False, False]
posted @   我是小菜鸡丫丫  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示