Python函数式编程:从入门到走火入魔

一行代码显示“爱心”

>>> print'
'.join([''.join([('AndyLove'[(x-y)%8]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15,-15,-1)])

Python函数式编程:从入门到走火入魔

# @file: data.py
import random  
from collections import namedtuple

Student = namedtuple('Student', ['id', 'ans'])

N_Questions = 25  
N_Students = 20

def gen_random_list(opts, n):  
    return [random.choice(opts) for i in range(n)]

# 问题答案 'ABCD' 随机
ANS   = gen_random_list('ABCD', N_Questions)  
# 题目分值 1~5 分
SCORE = gen_random_list(range(1,6), N_Questions)

QUIZE = zip(ANS, SCORE)  
students = [  
    # 学生答案为 'ABCD*' 随机,'*' 代表未作答
    Student(_id, gen_random_list('ABCD*', N_Questions))
    for _id in range(1, N_Students+1)
]

print(QUIZE)  
# [('A', 3), ('B', 1), ('D', 1), ...
print(students)  
# [Student(id=1, ans=['C', 'B', 'A', ...

正常方法:

mport data  
def normal(students, quize):  
    for student in students:
        sid = student.id
        score = 0
        for i in range(len(quize)):
            if quize[i][0] == student.ans[i]:
                score += quize[i][1]
        print(sid, '	', score)
 
print('ID	Score
==================')  
normal(data.students, data.quize)  
"""
ID    Score  
==================
1      5  
2      12  
...
"""

函数式

def cal(quize):  
    def inner(student):
        filtered = filter(lambda x: x[0] == x[1][0], zip(student.ans, quize))
        reduced = reduce(lambda x, y: x + y[1][1], filtered, 0)
        print(student.id, '	', reduced)
    return inner
map(cal(QUIZE), students)  

其他好玩的东东

每天一小步,人生一大步!Good luck~
原文地址:https://www.cnblogs.com/jkmiao/p/6234882.html