lambda , zip , filter, map, reduce, enumerate - 6个神仙级别的函数
作者:互联网
print('-'*10,'Introducing Python_CN_Bill Lubanovic_Python语言及其应用','-'*10)
print('-'*10,'Python中不可错过的五个超有用的神仙级函数','-'*10)
print('-'*10,'6个神仙级别的函数: lambda , zip , filter, map, reduce, enumerate','-'*10)
### lambda函数
#egCSDN https://blog.csdn.net/m0_59164304/article/details/123797398?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-0-123797398-blog-124763983.pc_relevant_antiscanv2&spm=1001.2101.3001.4242.1&utm_relevant_index=3
answer = lambda a,b:a**2 + b**2 + 2*a*b
print(answer(3,6))
###下面4个例子来自最初2017年开始学习Python时,网上看极客学院中的例程,2022.5.20再零散温习
#eg1
a = lambda x:x+3
print('a(1) = ',a(1))
#eg2
b = lambda x,y,z:x+y
c = lambda x,y,z:x+y+z
print('b(x,y,z) = ',b(1,2,3))
print('c(x,y,z) = ',c(3,2,4))
#eg3
def d(t):
return lambda y:y+t
d1 = d(10) ### 怎样输出显示此调用的表达式,想显示出输出结果为: lambda y:y+10
#type(d1)
print(d1(7))
#eg4
def m():
return lambda s:s*3
k = m()
print(k('Hello '))
### filter函数
def is_positive(a):
return a>0 ###如想输出结果分成2行,同时输出2种情况 a>0、a<0的数据怎么做?
output = list(filter(is_positive,[1,-2,3,-4,5,6]))
print(output)
def is_odd(n):
return n % 2 ==1
old_list = [1,2,3,4,5,6,7,8,9,10]
new_list = filter(is_odd,old_list)
print('过滤出的奇数 = ',list(new_list))
### zip函数
user_id = ['12121','56161','33287','23244']
user_name = ['范静芳','赵琴','欧阳芳','敏敏',]
user_info = list(zip(user_name,user_id))
print(user_info)
#另外一个zip例子:
colors = ['red','yellow','green','black']
fruits = ['apple','pineapple','grapes','cherry']
for item in zip(colors,fruits):
print(item)
### map函数
def add_list(a,b):
return a+b
output = list(map(add_list,[2,6,3],[3,4,5]))
print(output)
#注解:注意点如下:
#map(function, iterables)
#add_list
def makeupper(word):
return word.upper()
colors = ['red','yellow','green','black']
colors_uppercase = list(map(makeupper,colors))
print(colors_uppercase)
#此外,我们还可以使用匿名函数lambda来配合map函数,这样可以更加精简。
colors_uppercase_2 = list(map(lambda x:x.upper(),colors))
print('使用匿名函数lambda来配合map函数 = ', colors_uppercase_2)
### reduce函数
import functools ### from functools import reduce
def sum_two_elements(a,b):
return a+b
numbers = [6,2,1,3,4]
result = functools.reduce(sum_two_elements,numbers)
print(result)
#此外,我们同样可以使用匿名函数lambda来配合reduce函数,这样可以更加精简。'
from functools import reduce
numbers = [1,2,3,4,5]
sum2 = reduce(lambda x,y:x+y,numbers)
print('使用匿名函数lambda来配合reduce函数 = ',sum2)
### emulate函数
colors = ['red','yellow','green','black']
result = enumerate(colors)
for count,element in result:
print(f"迭代编号:{count},对应元素:{element}")
标签:map,函数,zip,reduce,list,colors,print,###,lambda 来源: https://www.cnblogs.com/CDPJ/p/16296943.html