Python的函数式编程,要用到lambda函数和map()函数,核心代码不少于三十行,急!
感觉 你俩问题一样,
多写了 几个,看一下吧
https://ask.csdn.net/questions/7729851
class Person:
name = ''
age = 0
Date = ''
id = ''
def say_some(self):
return f'我是克隆体:{self.name} 号,出生于 {self.Date}'
# 获取 一个集合数据
from datetime import datetime
def get_Person_List(name):
arr = []
for x in range(0, 50): # 循环50 次
ser = '_{:0>3d}'.format(x + 1) # 格式化3位数序号,位数不够0 补位
per = Person()
per.id = x + 1
per.name = name + ser
per.age = 13
per.Date = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") # 格式化时间
per.say_some()
arr.append(per)
return arr
def print_str(x):
print(x.name)
print(x.age)
print(x.say_some())
def is_prime1(n):
return len(list(filter(lambda i: n % i == 0, range(2, n)))) == 0
mm = lambda x: x + 2 # lambda 作为赋值给变量,变量作为函数
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# 直接调用 lambd 匿名方法
print(mm(1))
# 处理集合数据
lst = get_Person_List('张三')
list(map(lambda x: print_str(x), lst)) # 使用lambda 匿名函数,map() 返回迭代器,list()转换为列表
# 求 ls 中 素数的和
sum = 0
ls = [23, 45, 67, 87]
for x in ls:
if is_prime1(x):
sum = sum + x
print(sum)
好哥哥们,晚上9点就要交辣,555~
题目呢。。
需求是什么?总得有个数据吧?
# -*- coding:utf-8 -*-
def fun1(lst):
# 列表中所有元素都开平方
return list(map(lambda x:x**2,lst))
lst = [1,2,3,4]
print(fun1(lst)) # [1,4,9,16]
def fun2(a,b,c):
# 判断三角形是否为直角三角形
t = a,b,c
return sum(map(lambda x:x**2,t)) == max(t)**2*2
a,b,c = 3,4,5
if fun2(a,b,c):
print('直角三角形!')
else:
print('非直角三角形!')
def fun3(a, b):
res = map(lambda x:x[0]+x[1],zip(a,b))
return list(res)
a = [1,2,3]
b = [2,2,2]
print(fun3(a,b)) #[3, 4, 5]
↓↓↓如有帮助请点个采纳,谢谢!