Python刷题系列(3)_lambda函数(上)

简介: 编写一个 Python 程序来创建一个 lambda 函数,该函数将 15 作为参数传入的给定数字相加,还创建一个 lambda 函数,将参数 x 与参数 y 相乘并打印结果。

Python Lambda



1、创建一个 lambda 函数


编写一个 Python 程序来创建一个 lambda 函数,该函数将 15 作为参数传入的给定数字相加,还创建一个 lambda 函数,将参数 x 与参数 y 相乘并打印结果。

r = lambda a : a + 15
print(r(10))
r = lambda x, y : x * y
print(r(12, 4))
'''
25
48
'''


2、接受一个参数的函数,且该参数乘以给定数字


编写一个Python程序来创建一个接受一个参数的函数,该参数将乘以未知的给定数字。

def func_compute(n):
 return lambda x : x * n
result = func_compute(2)
print("Double the number of 15 :", result(15))
result = func_compute(3)
print("Triple the number of 15 :", result(15))
result = func_compute(4)
print("Quadruple the number of 15 :", result(15))
result = func_compute(5)
print("Quintuple the number 15 :", result(15))
'''
Double the number of 15 : 30
Triple the number of 15 : 45
Quadruple the number of 15 : 60
Quintuple the number 15 : 75
'''

3、使用 Lambda 对元组列表进行排序



编写一个 Python 程序,使用 Lambda 对元组列表进行排序。

元组的原始列表:

[(‘English’, 88), (‘Science’, 90), (‘Maths’, 97), (‘Social sciences’, 82)]

排序元组列表:

[(‘Social Sciences’, 82), (‘English’, 88), (‘Science’, 90), (‘Maths’, 97)]


方法一:使用sort函数

subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
print("Original list of tuples:")
print(subject_marks)
subject_marks.sort(key = lambda x: x[1])
print("\nSorting the List of Tuples:")
print(subject_marks)
'''
Original list of tuples:
[('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
Sorting the List of Tuples:
[('Social sciences', 82), ('English', 88), ('Science', 90), ('Maths', 97)]
'''

这里使用sort函数中的参数key:

关于参数key :为函数,指定取待排序元素的哪一项进行排序,函数用上面的例子来说明,代码如下:

students  =  [( 'john' ,  'A' ,  15 ), ( 'jane' ,  'B' ,  12 ), ( 'dave' ,  'B' ,  10 )]
sorted (students, key = lambda  student : student[ 2 ])

key指定的lambda函数功能是去元素student的第三个域(即:student[2]),因此sorted排序时,会以students所有元素的第三个域来进行排序

方法二:使用sorted函数

subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
print("Original list of tuples:")
print(subject_marks)
a=sorted(subject_marks,key = lambda x: x[1])
print("\nSorting the List of Tuples:")
print(a)
'''
Original list of tuples:
[('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
Sorting the List of Tuples:
[('Social sciences', 82), ('English', 88), ('Science', 90), ('Maths', 97)]
'''


4、使用 Lambda 对字典列表进行排序


编写一个 Python 程序来使用 Lambda 对字典列表进行排序。

models = [{'make':'Nokia', 'model':216, 'color':'Black'}, 
          {'make':'Mi Max', 'model':2, 'color':'Gold'}, 
          {'make':'Samsung', 'model': 7, 'color':'Blue'}]
print("Original list of dictionaries :")
print(models)
sorted_models = sorted(models, key = lambda x: x['model'])
print("\nSorting the List of dictionaries :")
print(sorted_models)
'''
Original list of dictionaries :
[{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': 2, 'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}]
Sorting the List of dictionaries :
[{'make': 'Mi Max', 'model': 2, 'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}, {'make': 'Nokia', 'model': 216, 'color': 'Black'}]
'''

对于字典的排序,就不能使用对元组的排序sort了,而是需要使用sorted函数。

sorted() 函数对所有可迭代的对象进行排序操作:

sorted(iterable, cmp=None, key=None, reverse=False)


sort 与 sorted 区别:

1、sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

2、list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。


【iterable】 可迭代对象。


【cmp】 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。(一般省略)


【key】主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。

常用的用来作为参数key的函数有 lambda函数和operator.itemgetter()

尤其是列表元素为多维数据时,需要key来选取按哪一位数据来进行排序


【reverse】 排序规则,reverse = True 降序 , reverse = False 升序(默认)。


5、使用 Lambda 过滤整数列表


编写一个 Python 程序来使用 Lambda 过滤整数列表。

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list of integers:")
print(nums)
print("\n偶数:")
even_nums = list(filter(lambda x: x%2 == 0, nums))
print(even_nums)
print("\n奇数:")
odd_nums = list(filter(lambda x: x%2 != 0, nums))
print(odd_nums)
'''
Original list of integers:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
偶数:
[2, 4, 6, 8, 10]
奇数:
[1, 3, 5, 7, 9]
'''

如果不是匿名函数的写法:

def is_odd(n):
    return n%2 == 1
lst1 = list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10]))
print(lst1)
'''
[1, 3, 5, 7, 9]
'''

【1】filter

filter()函数用于过滤序列,过滤掉不符合条件的元素,返回符合条件的元素组成新列表。


filter()函数是python内置的另一个有用的高阶函数


filter()函数接收一个函数f和一个list


这个函数f的作用是对每个元素进行判断,返回True或False


filter()根据判断结果自动过滤掉不符合条件的元素


返回由符合条件元素组成的新list


3.7.3版filter需要嵌套在list里面

filter(function,iterable) 
# 其中function为函数,iterable为序列


6、使用 Lambda 查找是否以给定字符开头


编写一个 Python 程序,以使用 Lambda 查找给定字符串是否以给定字符开头。

starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Python'))
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Java'))
'''
True
False
'''

关于startswith函数,返回的是布尔值:

print('Java'.startswith('P'))
'''
False
'''


7、使用 Lambda 提取年、月、日期和时间


编写一个 Python 程序,使用 Lambda 提取年份、月份、日期和时间。

import datetime
now = datetime.datetime.now()
print(now)
year = lambda x: x.year
month = lambda x: x.month
day = lambda x: x.day
t = lambda x: x.time()
print(year(now))
print(month(now))
print(day(now))
print(t(now))
'''
2022-05-08 09:58:33.843320
2022
5
8
09:58:33.843320
'''


8、使用 Lambda 创建 Fibonacci


编写一个Python程序,使用Lambda创建Fibonacci系列,直到n。

from functools import reduce
fib_series = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]],
                                range(n-2), [0, 1])
print("Fibonacci series upto 2:")
print(fib_series(2))
print("\nFibonacci series upto 5:")
print(fib_series(5))
print("\nFibonacci series upto 6:")
print(fib_series(6))
print("\nFibonacci series upto 9:")
print(fib_series(9))
'''
Fibonacci series upto 2:
[0, 1]
Fibonacci series upto 5:
[0, 1, 1, 2, 3]
Fibonacci series upto 6:
[0, 1, 1, 2, 3, 5]
Fibonacci series upto 9:
[0, 1, 1, 2, 3, 5, 8, 13, 21]
'''

2】reduce

reduce的语法格式

reduce(function, sequence[, initial]) -> value

reduce函数接受一个function和一串sequence,并返回单一的值,以如下方式计算:


初始,function被调用,并传入sequence的前两个items,计算得到result并返回

function继续被调用,并传入上一步中的result,和sequence种下一个item,计算得到result并返回。一直重复这个操作,直到sequence都被遍历完,返回最终结果。

initial:指定的初始值

注意1: 当initial值被指定时,传入step1中的两个参数分别是initial值和sequence的第一个items。reduce()最多只能接受三个参数,func,sequence,initial。

注意2:在python2中reduce时内置函数,但是在python3中,它被移到functools模块,因此使用之前需要导入。


9、使用 Lambda 查找两个给定数组的交集


编写一个 Python 程序,使用 Lambda 查找两个给定数组的交集。

array_nums1 = [1, 2, 3, 5, 7, 8, 9, 10]
array_nums2 = [1, 2, 4, 8, 9]
print("Original arrays:")
print(array_nums1)
print(array_nums2)
result = list(filter(lambda x: x in array_nums1, array_nums2)) 
# 这里的第二个参数是filter的参数
print ("\nIntersection of the said arrays: ",result)
'''
Original arrays:
[1, 2, 3, 5, 7, 8, 9, 10]
[1, 2, 4, 8, 9]
Intersection of the said arrays:  [1, 2, 8, 9]
'''


10、使用 Lambda 对数组中奇偶数进行计数


编写一个 Python 程序,以使用 Lambda 重新排列给定数组中的正数和负数。

array_nums = [1, 2, 3, 5, 7, 8, 9, 10]
print("Original arrays:")
print(array_nums)
odd_ctr = len(list(filter(lambda x: (x%2 != 0) , array_nums)))
even_ctr = len(list(filter(lambda x: (x%2 == 0) , array_nums)))
print("\nNumber of even numbers in the above array: ", even_ctr)
print("\nNumber of odd numbers in the above array: ", odd_ctr)
'''
Original arrays:
[1, 2, 3, 5, 7, 8, 9, 10]
Number of even numbers in the above array:  3
Number of odd numbers in the above array:  5
'''


11、使用 Lambda 在给定列表中查找长度为 6 的值


编写一个 Python 程序,以使用 Lambda 查找给定列表中长度为 6 的值。

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
days = filter(lambda day: day if len(day)==6 else '', weekdays)
for d in days:
  print(d)
'''
Monday
Friday
Sunday
'''


12、使用map和lambda添加两个给定列表


编写一个Python程序,使用map和lambda添加两个给定的列表。

nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
print("Original list:")
print(nums1)
print(nums2)
result = map(lambda x, y: x + y, nums1, nums2)
print("\nResult: after adding two list")
print(list(result))
'''
Original list:
[1, 2, 3]
[4, 5, 6]
Result: after adding two list
[5, 7, 9]
'''

【3】map

map是python内置函数,会根据提供的函数对指定的序列做映射。

map()函数的格式是:

map(function,iterable,...)


1、第一个参数接受一个函数名,后面的参数接受一个或多个可迭代的序列,返回的是一个集合。

2、把函数依次作用在list中的每一个元素上,得到一个新的list并返回。

3、map不改变原list,而是返回一个新list。


13、使用 Lambda 查找可被19或13整除的数字


编写一个Python程序,从使用Lambda的数字列表中查找可被十九或十三整除的数字。

nums = [19, 65, 57, 39, 152, 639, 121, 44, 90, 190]
print("Orginal list:")
print(nums) 
result = list(filter(lambda x: (x % 19 == 0 or x % 13 == 0), nums)) 
print("\nNumbers of the above list divisible by nineteen or thirteen:")
print(result)
'''
Orginal list:
[19, 65, 57, 39, 152, 639, 121, 44, 90, 190]
Numbers of the above list divisible by nineteen or thirteen:
[19, 65, 57, 39, 152, 190]
'''


相关文章
|
2月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
178 1
|
2月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
270 1
|
2月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
163 0
|
3月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
273 101
|
3月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
216 99
|
3月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
192 98
|
3月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
4月前
|
Python
Python 函数定义
Python 函数定义
524 155
|
3月前
|
算法 安全 数据安全/隐私保护
Python随机数函数全解析:5个核心工具的实战指南
Python的random模块不仅包含基础的随机数生成函数,还提供了如randint()、choice()、shuffle()和sample()等实用工具,适用于游戏开发、密码学、统计模拟等多个领域。本文深入解析这些函数的用法、底层原理及最佳实践,帮助开发者高效利用随机数,提升代码质量与安全性。
657 0
|
4月前
|
数据挖掘 数据处理 C++
Python Lambda:从入门到实战的轻量级函数指南
本文通过10个典型场景,详解Python中Lambda匿名函数的用法。Lambda适用于数据处理、排序、条件筛选、事件绑定等简洁逻辑,能提升代码简洁性和开发效率。同时提醒避免在复杂逻辑中过度使用。掌握Lambda,助你写出更高效的Python代码。
220 0

推荐镜像

更多