Authentic Python (i)

Source: Internet
Author: User

Zhang Yang

Forced lattice

The fruit Company's "the bigger than bigger" advertisement word, causes the force lattice to enter the public view. Built-in grid artifact Program Ape Hearts must be yearning for a higher force lattice. Ask yourself if you are dreaming of such a scene:

When you write the next line of code, the person next to the incredible wide-eyed, indicating that the original code can be written like this?

This is how a journey of X-Pack. Python can help you achieve that desire.

Python is very easy for laymen to get started with. At the same time, for those of us who use C language, and even the main use of C language in the work of the program, use it has a natural barrier. How does this make the hard-pressed handlers maintain dignity in front of the layman? Don't worry, please keep looking.

Idiomatic language

Everyone who has studied English knows that the English we are speaking is actually Chinglish, while the Indians speak a language called hinglish, which is why it is much more difficult for us to listen to the Hollywood soundtrack than to listen to Chinese speaking English. Each language, every group of people, will have their own idioms-idioms. The same is true of programming languages, especially in many high-level languages, which have their own unique parts, and that is why they are needed or not needed. Like a bad programmer, the C language used to write C + + code, the compiler does not have a problem, but why do not you directly write C file?!

Let's take a look at the following piece of code:

 def count_person_c()f = open(' data.csv ')  Try:        data = F.read ()finally: F.close () groups = {} lines = Data.splitlines () forIinchXrange (len (lines)): Name = Lines[i].split (', ')[0] Age = Lines[i].split (', ')[1] Sex = Lines[i].split (', ')[2] Yow = Lines[i].split (', ')[3] Salary = Lines[i].split (', ')[4] tax = lines[i].split (', ')[5] Bonus = Lines[i].split (', ')[6]if(Sex = =' Male '  andInt (age) > -)or(Sex = =' Female '  andInt (age) > -): person = int (YOW) * (int (Salary)-Int. (tax) + int (bonous)) *0.9            ifName not inchGroups:groups[name] = [] groups[name].append (person) forKeyinchGroupsPrintKey'---> ', Groups[key]

This is done using the Python syntax, and can also be performed using the Python interpreter. But, please look carefully again, do you feel familiar? In addition to using the native dictionary type of Python, what is the python thing? This kind of forcing is about the same height as the Mariana Trench.

To pursue a higher force, Python has always been a human rather than a machine to think about the problem, we will continue to see this example.

The law of Egg pain

If there is one thing that makes your egg ache, then there must be an egg-sore person to help you finish it.

Assign value

In the example of the most bright blind titanium alloy eyeball is that 7 rows of neat assignment statement. From the machine's point of view, they are one-by-one assignment statements, perfect. But from a human point of view, these things seem to make a person's egg pain: It is clear from the same piece of data extracted from the value, why the program language requirements to use this line to get it? In fact, such code, in the C language and many other languages, is considered unavoidable, and what programmers can do is make them look neat and painless.

The egg-sore Python does not think this should be an assignment of many steps, but should be a unpacking statement, so it should be fully implemented in one line, as follows:

name, age, sex, yow, salary, tax, bonus = lines[i].split(‘,‘)

Here to say a small piece of personal feelings, if Python code often see the shape of the name[i], name[1], name[key] form, that the landlord's machine poison has been quite deep. Must destroy them, and there must be a way to destroy them, forcing lattice is quite low.

Back to the text, similar to the example, when the programmer in the computer language learning, must be the teacher asked to write a program, to exchange the value of two variables; egg-sore programmers are sometimes asked not to use a third variable cache. This kind of egg-ache thing, still in many schools continue to happen. In Python, the egg-sore people think that the value exchange, should be a simple statement implementation, more than one line of statements is insulting their IQ, so in Python we can do this:

aa
Cycle

When the egg-sore handlers Learn the C language, they are hinted that the loop needs to be +1/-1 by the index, so I, J, K become the most common variable name in the program, and almost as soon as you see it, it's conditioned to think that they should be an index in a loop (clean The code book says so.) But in fact, looping through a bit does not necessarily require an index, it will bring some confusion. Almost every loop is written with extra consideration: whether the index starts at 0 or starts at 1, and where it ends-1. Crossing Remember, do you use an index in your mind when you do a vector calculation in a linear algebra homework? Yes, no need, look at the eyes, finger gestures on the line. Just the damned Turing needs an index, and the person who sees the index will have a sore egg. The egg-sore Python loops like this:

forin [1234]:

Variable A is to be 1, 2, 3, 4, where the index is not needed, will force people to think about the machine angle, increase the unnecessary difficulty. Opponents are bound to say that indexes allow loops to be traversed in reverse order. Please be calm, the following can achieve 4, 3, 2, 1 traversal.

D = [1234]forinD[::-1]:

In spite of this, the pain of the egg will still occur, sometimes the program really needs to index, especially need to put the index value as a parameter to the loop body call function, what to do? Egg-sore Python There are also scenarios: enumerate (colors), which can return a pair of values: index, variable, as shown below.

forin enumerate([1234]):

Python's for also has a magical place that is called For-else. In a program, there are often scenarios in which a loop iterates through a linked list, and if the desired member is found, it returns to its position immediately, otherwise it must have found all the elements.

ages = [4221183319Trueforin ages:    if18:        False        breakif are_all_adult:    print‘All are adults!‘

If it's a C language, it's good. But in Python, it also has a place where the egg hurts, because it can be like this:

ages = [4221183319]forin ages:    if18:        breakelse    print‘All are adults!‘

When a break in a loop is not executed, the last loop goes into the else execution; the egg-sore people. It also has an egg-sore name, which is more aptly said to be un-break.
Of course, Python has another high-forcing method to implement this function, which requires only two lines of code, as described later.

Dictionary

All that's said is a common list loop, Python's unique data type: The dictionary loop, the value of the variable is just the key value of the dictionary without the contents of the entry:

forkeyin groups:   key‘--->‘, groups[key]

See Groups[key], the egg pain again hit. Yes, the circle of the dictionary in Python should not be this way, it has designed itself like this:

forin groups.items():   print‘--->‘, value

Yes, that's what you see. The key value and the item content are returned in pairs, and there is a possible additional benefit: when the dictionary becomes very large, the items () are changed to Interitems (), it is very effective to improve the performance of Python, but also save memory, this is called an iterator, Will be mentioned later in this article.

Speaking of dictionaries, follow this piece of code:

groups = {}    ...    ifnotin groups:        groups[name] = []    groups[name].append(person)

This is a C programmer writes typical Python code, not only has the groups[name of the egg ache], also has the multilayer indentation, the judgment, assigns the value empty list, is simply the egg pain plus three level. According to the law of egg pain, there must be people with egg pain to help solve this problem:

groups = {}...   groups.setdefault(name, []).append(pension)

or a

groups = defaultdict(list)...   groups[name].append(pension)

The dictionary groups automatically invokes the function list to create an empty list only if name appears for the first time as a key value, and the append behavior of the list is called directly if it already exists. Small series prefer the second way of writing, when inserting the code is more concise and clear. Now how to see, how to think groups = {} is in the definition of variables, egg pain ah ...

Authentic Python (i)

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.