Authentic Python (ii)

Source: Internet
Author: User

Zhang Yang

List derivation

The above describes a high-forcing method of creating a dictionary, what about the list? According to the law of egg pain, it must have, but it has been a very painful name, called List deduction:
Let's take a look at this code:

li = []forain A:    ifa%20:        li.append(a)

See the first line of code, the small series has no longer want to see, yes, this is the real change in C language. The egg pain index is soaring to the sky. The Python line is supposed to take care of it.

li = [aforainifa%20]

The list generated above contains the odd elements that are picked out from List A. High-force lattice? One line is done! Because, the circular judgment here is not for the machine to see, but to let people understand. Read from left to right: The list contains element A on the one hand from List A, and it conforms to a condition that is not 0 by 2.

Said so much, yours faithfully crossing can change the example 1, let it get it deserved to force lattice?

 def reach_age_limit(personal_info):Name, age, sex, yow, salary, tax, bonus = Personal_info>split (', ')returnF (Sex = =' Male '  andInt (age) > -)or(Sex = =' Female '  andInt (age) > -) def Calculate_person(personal_info):Name, age, sex, yow, salary, tax, bonus = Personal_info>split (', ')returnint (YOW) * (int (salary)-int (tax) + int (bonous)) *0.9 def get_name(personal_info):Name, age, sex, yow, salary, tax, bonus = Personal_info>split (', ')returnName def Count_person():     withOpen' Data.csv ') asF:data = F.read () target_persons = [D forDinchData.splitlines ()ifReach_age_limit (d)] groups = {} forPersoninchTarget_persons:groups.setdefault (get_name (person), []). Append (Calculate_person (person)) forKey, ValueinchGroups.items ():PrintKey'---> ', value

Is that OK? Is there any other way? There is also an example of a higher force:

def count_person():    with open(‘data.csv‘as f:        data = f.read()    groups = {get_name(person):caculate_person(person)              forin data.splitlines()              if reach_age_limit(person)}    forin groups.items():        print‘--->‘, value

The extracted three functions, if aggregated into a class, are much higher perfect.

The example is finished, this article should be finished? No, no, no, let you guess the end, the small series of egg pain ...

Now the industry's fiery functional programming, how does Python support it? There must be some egg-sore Python people do something so that we can be a bit taller.

Cache

Starting with the following example,

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

This function has a function of opening the specified URL, and a subordinate function: Caching the previously opened URL; Strictly speaking, this violates the single principle of responsibility; the egg-sore Python man gives the following scenario:

@cachedef web_lookup(url)    return urllib.urlopen(url).read()def cache(func)    saved = {}    @wraps    def new_func(*args):        ifnotinsaved:            saved[args] = func(*args)        return saved[args]    return new_func

In the cache function, for the function modified by the cache, a cache is made for the input parameters and return values, and the resulting new function is returned. Thus, each time the web_lookup is called, it is actually called the input, the output is cached after the new function, rather than the literal original function. Python supports functions with the same name, do you remember that crossing?

Combine

Suppose a calculator is implemented, a key sequence 28++32+++32+39 is received, and the result of the calculation is obtained using Python

‘28++32+++32+39‘0fortokenin expr.split(‘+‘):    iftoken:        res += int(token)

This is the code under the C language logic, and the people who have egg pain in Python can simply not apply any new variables, directly using three functions to combine:

sumfilter(bool, expr.split(‘+‘))))

The first function filter (pred, seq) –> [t-T in seq if pred (t)], excluding elements that do not conform to the bool condition;
The second function map (fun, seq) –> [func (t) for T in seq], this is actually a mathematical mapping definition, for the machine is a loop, but people are more concerned about the mapping relationship (very high-level domain), This makes it easier for the compiler to optimize (for example, to compute all the sequences in parallel).
The third function sum, as its name implies, is the sum of all the elements in the list.

At this point, the small part is full of mathematical nouns, the program language has been completely discarded: the list of empty strings, and then map the string as an integer, and finally the sum of all elements.

All

I used an example of a loop before, and actually it can be implemented in a higher-force lattice:

ages = [4221183319]if all(map(lambda a:a>=18, ages)):   print‘All are adults!‘

Lambda is used to construct a function, input parameter A, return a>=18;
Map maps all the elements in the ages to a list of true/false;
All returns whether all elements in the list are true

See here, yours faithfully crossing have feelings? The loop is a very low-force grid for machines, and Python programmers should alienate it and avoid it.

Now really want to say goodbye, the last sentence:

Python is the path of x to repair far, Wu bei will go up and down and quest.

Authentic Python (ii)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.