地道的 Python(二)

作者: Zhang Yang

列表推导

上文介绍了一个高逼格的创建字典的方法。那列表呢?依据蛋痛定律,它也一定有,可是它被起了一个很蛋痛的名字,叫列表推导:
先看看这种代码:

li = []
for a in A:
    if a%2 != 0:
        li.append(a)

看到代码第一行的时候,小编已经不想再看下去了,是的,这才真正的万变不离 C 语言。蛋痛指数直冲云霄了。

Python 里一行就应该搞定它

li = [a for a in A if a%2 != 0]

上文产生的列表包括:从列表A里挑出来的奇数的元素。高逼格吗?一行搞定。由于。这里的循环推断语句不是给 机器 看的,而是让 人 来理解的。

从左向右读就能够了:列表中包括元素a一方面来自于列表A,同一时候它符合除以2余数不为0的条件。

说了这么多。列位看官能够动手改改样例1。让它得到它应得逼格了吗?

def reach_age_limit(personal_info):
    name, age, sex, yow, salary, tax, bonus = personal_info>split(',')
    return f( sex == 'Male' and int(age) > 60 ) or
          ( sex == 'Female' and int(age) > 55 )

def calculate_person(personal_info):
    name, age, sex, yow, salary, tax, bonus = personal_info>split(',')
    return  int(yow) * ( int(salary) - int(tax) + int(bonous) ) * 0.9

def get_name(personal_info):
    name, age, sex, yow, salary, tax, bonus = personal_info>split(',')
    return name

def count_person():
    with open('data.csv') as f:
        data = f.read()
    target_persons = [ d for d in data.splitlines() if reach_age_limit(d) ]

    groups = {}
    for person in target_persons:
        groups.setdefault(get_name(person),[]).append(calculate_person(person))

    for key, value in groups.items():
        print key, '--->', value    

这就能够了吗?还有别的方法吗?另一个更高逼格的样例:

def count_person():
    with open('data.csv') as f:
        data = f.read()

    groups = {get_name(person):caculate_person(person)
              for person in data.splitlines()
              if reach_age_limit(person)}

    for key, value in groups.items():
        print key, '--->', value

抽取出来的三个函数,如果聚集到某个类中,就更高 perfect 了。

样例讲评完了。本文就该结束了吗?不,不,不。让你猜到结局。小编的要蛋痛了。。。

如今业界火热的函数式编程,Python 怎么支持的? 一定有蛋痛的 Python 人做了些什么,让我们能够更高逼格一些。


Cache

从以下的样例開始。

def web_lookup(url, cache={}):
    if url not in cache:
        cache[url] = urllib.urlopen(url).read()
    return cache[url]

这个函数有一个功能:打开指定的url;另一个附属功能:缓存之前打开过的url。严格来说,这违反了单一职责原则;蛋痛的 Python 人给出了例如以下的方案:

@cache
def web_lookup(url)
    return urllib.urlopen(url).read()

def cache(func)
    saved = {}
    @wraps
    def new_func(*args):
        if args not in saved:
            saved[args] = func(*args)
        return saved[args]
    return new_func

cache 函数里。针对被cache修饰的函数。做了一个针对输入參数和返回值的缓存。产生的新函数被返回。这样,每次web_lookup被调用的时候。实际上被调用的是输入、输出被缓存后的新函数,而不是字面原来的那样的函数。Python 支持同名函数,看官们还记得吗?


Combine

如果实现一个计算器,接收到按键序列28++32+++32+39,使用 Python 得出计算结果

expr, res = '28++32+++32+39', 0
for token in expr.split('+'):
    if token:
        res += int(token)

这是 C 语言逻辑下的代码。而 Python 中蛋痛的人们全然能够不适用不论什么新增变量,直接使用三个函数进行组合:

res = sum(map(int, filter(bool, expr.split('+'))))

第一个函数filter(pred, seq) –> [t for t in seq if pred(t)],剔除不符合bool条件的元素。
第二个函数map(fun, seq) –> [func(t) for t in seq],这个实际上就是数学上的映射的定义,对于机器来说就是循环。可是 人 更关注的是映射关系(很高层次的领域),这样编译器更easy去优化(比如并行计算全部的序列)。


第三个函数sum。顾名思义就是对列表里全部元素。求和。

此时小编已满脑数学名词了,程序语言已经全然被抛弃:先剔除列表中的空串,然后映射字符串为整数,最后对全部元素求和。


All

之前介绍循环时用过一个样例。实际上它还能够更高逼格的实现:

ages = [42, 21, 18, 33, 19]
if all(map(lambda a:a>=18, ages)):
   print 'All are adults!'

lambda用来构造一个函数,输入參数a,返回a>=18;
map将ages里全部元素映射为由True/False组成的列表;
all返回列表内全部元素是否都为True

看到这里。列位看官有感觉了吗?循环是给 机器 使用的绝低逼格东东,Python 程序猿们应该疏远它,避免它。

如今真的要说再见了,最后一句:

Python 装X之路其修远兮,吾辈将上下而求索。

posted @ 2018-02-03 16:45  zhchoutai  阅读(155)  评论(0编辑  收藏  举报