赞
踩
def twoSum(num1: int, num2: int) -> int:
return num1 + num2
print(twoSum(10, 20))
运行结果:30
numSum = lambda num1, num2: num1 + num2
print(numSum(10, 20))
运行结果:30
leapYear1 = lambda year: '闰年' if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else '平年'
print(leapYear1(2000))
leapYear2 = lambda year: (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
print(leapYear2(2000))
运行结果:闰年
True
def A():
return '这是函数A'
print(A())
a = A()
print(a())
运行结果:这是函数A
这是函数A
def B(func):
print(func())
return '这是函数B'
print(B(A))
运行结果:这是函数A
这是函数B
nums = [10, 5, 21, 33, 98, 19]
print(max(nums))
def func(element): # 这个形参指向nums列表中每一个比较大小的元素
return element % 10 # 返回值,返回了余数,要把这个余数称为 max 比较大小的规则
print(max(nums, key=func)) #max函数就会按照我们指定的根据余数判断谁是最大值
print(max(nums, key=lambda x: x % 10))
运行结果:98
19
19
nums = [10, 5, 21, 33, 98, 19]
print(sorted(nums))
print(sorted(nums, reverse=True))
def func_1(element):
return element % 10
print(sorted(sum, key=func_1))
运行结果:[5, 10, 19, 21, 33, 98]
[98, 33, 21, 19, 10, 5]
[10, 21, 33, 5, 98, 19]
nums = [10, 5, 21, 33, 98, 19]
def func_2(element):
return str(element)
print(list(map(func_2, nunms)))
print(list(map(lambda element: element * 2, nums)))
print(list(map(lambda element1, element2: (element1, element2), nums, nums)))
运行结果:['10', '5', '21', '33', '98', '19']
[100, 25, 441, 1089, 9604, 361]
[(10, 10), (5, 5), (21, 21), (33, 33), (98, 98), (19, 19)]
from functools import reduce lettets = ['1', '2', '3', '4', '5'] def func_3(x, element): return x + element # 将letters中每个字符串拼接在一起 print(reduce(func_3, letters, '')) # 将letters中每个元素转为整形求和 print(reduce(lambda x, element: int(element) + x, letters, 0)) # 将letters中每个元素转为整型求累积 print(reduce(lambda x, element: int(element) * x, letters, 1)) 运行结果:12345 15 120
names = ['张三', '李四', '小明', '小红']
math = [90, 89, 88, 99]
english = [98, 78, 66, 82]
chinese = [23, 98, 100, 72]
result = list(map(lambda x, y, m, n: {'name':x, 'math':y, 'english':m, 'chinese':n}, name, math, english, chinese))
print(result)
运行结果:[{'name': '张三', 'math': 90, 'english': 98, 'chinese': 23}, {'name': '李四', 'math': 89, 'english': 78, 'chinese': 98}, {'name': '小明', 'math': 88, 'english': 66, 'chinese': 100}, {'name': '小红', 'math': 99, 'english': 82, 'chinese': 72}]
from functools import reduce
result = reduce(lambda result_init, x: x * result_init, [i for i in range(1, 11)])
print(result)
运行结果:3628800
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。