编程语言
首页 > 编程语言> > Python zip(), map(), filter(), reduce()

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]

标签:map,False,Python,list,reduce,filter,print,True
来源: https://www.cnblogs.com/kxtomato/p/16516063.html