1.重复一个字符串N次
1 repeatChar=lambda char,n:char*n In [1]:repeatChar('c',5) Out [1]:'ccccc'
2.列表排序
2 a = [(1, 2), (4, 1), (9, 10), (13, -3)] a.sort(key=lambda x: x[1]) print(a) # Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
3. 三元运算符
3 def getPoints(answers, p): questionPoints = lambda i,ans: (i+1) if ans else -p res = 0 for i, ans in enumerate(answers): res += questionPoints(i, ans) return res
三元运算符定义:
#如果条件为真,返回真 否则返回假 condition_is_true if condition else condition_is_false
4. 字符列表排序
用姓氏按照字典顺序排列学生名。如果两个学生碰巧有相同的姓氏,他们的结果顺序应该与原始列表中的顺序相同。
4 def sortStudents(students): students.sort(key= (lambda s:s.split()[-1]) ) return students
输入:
students = ["John Smith", "Jacky Mon Simonoff", "Lucy Smith", "Angela Zimonova"]
输出:
sortStudents(students) = ["Jacky Mon Simonoff", "John Smith","Lucy Smith", "Angela Zimonova"]
5. 各位数字求和
给定的一个整数,譬如
a=1234
对各位数字求和,结果为result=10
.5 a=1234 digitSum=lambda x:sum(map(int,list(str(x)))) sm=digitSum(a) print(sm) #Output: 10
Lambda表达式实例
最新推荐文章于 2023-10-02 11:25:59 发布