内置函数-map、filter、zip

### zip ### --- 就是把 list ,合并到一起

a = ['a','b','c']

b = [1,2,3]

得到:a 1,b 2,c 3

# for a,b in zip(a,b):
#   print(a,b)

print(list(zip(a,b))) ----- 将一维数组变成 二维;以长度小的数组为准

### map ### ----- 循环调用函数

def my(num):
  return str(num)


lis = [1,2,3,45,6,7,8]

#new_list = []
#for i in lis:
#    print(i)
#   new_list.append(my(i))
#print(new_list)

res = map(my,lis) ------- 与上述循环结果一致;直接用 map 循环调用函数;前面是函数名,后面是 iter
print(list(res))

### filter ### ---- 也是循环调用函数,filter 只保留返回为真的数据

def even(num):
  if num % 2 == 0:
    return True
  return False

lis = [1,2,3,4,5,6,7]

res = filter(even,lis)

resa = map(even,lis)

print(list(res)) -------- 结果:[2, 4, 6];filter 只保留返回为真的数据

print(list(resa)) -------- 结果:[False, True, False, True, False, True, False];map 只返回函数结果

猜你喜欢

转载自www.cnblogs.com/lynn-chen/p/9037673.html