Authentic Python (1)

Source: Internet
Author: User

Authentic Python (1)
Force Grid

The fruit company's advertisement word "The bigger than bigger" has pushed The company into The public's field of view. The inner heart of the programmers with built-in force grid Artifacts must be eager for a higher force grid. I am wondering if I have such a situation:

When you write a line of code at will, the people next to it suddenly open their eyes, indicating that the original code can be written like this?

This is a tour of X. Python can help you achieve this kind of desire.

Python is very easy for outsiders. At the same time, it is a natural obstacle for programmers who use C language and even use C language in their work. This allows hard-pressed programmers to maintain their dignity in front of their layers? Please wait.

Idioms

Everyone who has learned English knows that the English We Speak now is actually Chinglish, while Indians speak a language called Hinglish, this is why it is much more difficult for us to listen to the original Hollywood movies than to hear Chinese people speak English. Every language and group of people will have their own habits-idioms. The same is true for programming languages. Especially for many advanced languages, they all have their own unique things. This is why they are needed or not needed. Just like a lame programmer who is used to writing C ++ code in C language, there is no problem in compilation and execution, but why don't you directly write C files ?!

Let's take a look at the following code:

def count_person_c()    f = open('data.csv')    try:        data = f.read()    finally:        f.close()    groups = {}    lines = data.splitlines()    for i in xrange(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' and int(age) > 60 ) or          ( sex == 'Female' and int(age) > 55 ):            person = int(yow) * ( int(salary) - int(tax) + int(bonous) ) * 0.9            if name not in groups:                groups[name] = []            groups[name].append(person)    for key in groups:        print key, '--->', groups[key]

This is done using the Python syntax and can also be executed using the Python interpreter. However, please read it again carefully, do you feel familiar? In addition to the native dictionary type of Python, what is Python? This is almost the same height as the Mariana Trench.

To pursue a higher level of pressure, Python always considers problems from the perspective of humans rather than machines. We will continue to see such examples later.

Egg pain Law

If one thing hurts you, you must already have an egg.

Assignment

In this example, the most eye-catching blind titanium alloy is the seven neat assignment statements. From the machine's point of view, they are a perfect assignment statement. However, from the perspective of people, these things seem to be annoying: clearly, they are numerical values derived from the same piece of data. Why do programming languages require this to be used to obtain it? In fact, such code is considered inevitable in C and many other languages. What programmers can do is to make them look neat and don't hurt too much.

Python do not think this should be a value assignment for many steps, but an unpacking statement. Therefore, a line should be fully implemented, as shown below:

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

Here is a small part of my personal experience. If Python code is often shownname[i], name[1], name[key]The form indicates that the host's machine is already quite poisonous. They must be wiped out, and there must be a way to destroy them, so it is really low enough.

Back to the text. In a similar example, when programmers are learning computer languages, they must have been asked by their teachers to write a program to exchange the values of two variables; egg programmers are sometimes asked not to use the third variable cache. Such a thing is still happening in many schools. People in Python think that value exchange should be a simple statement implementation. More than one row of statements is insulting their IQ, so in Python we can do this:

a, b = b, a
Loop

When learning the C language, egg programmers are hinted that the loop requires the value recurrence through the index value + 1/-1, So I, j, k has become the most common variable name in the program. As soon as you see it, it is considered as a conditioned reflection, they should be indexes in a loop (this is exactly what the book Clean Code says ). But in fact, loop traversal does not necessarily require an index, but it will lead to some confusion. Almost every loop is written with additional considerations: whether the index starts from 0 or from 1; whether the index ends from-1. Looking back, have you used an index in your mind when doing vector computing in linear algebra homework? Yes, you don't need to. Just look at it with your eyes and just show your fingers. It's just a damn Turing machine that needs an index. It hurts to see the index. Python with egg pain loops like this:

 for d in [1, 2, 3, 4]:

Variable a is equivalent to 1, 2, 3, and 4 respectively. The index is not required here, which forces people to think about problems from the perspective of machines and increase unnecessary difficulty. Opponents will say that indexes can traverse loops in reverse order. Please calm down, as shown below, we can achieve traversal of 4, 3, 2, and 1.

D = [1, 2, 3, 4]for d in D[::-1]:

In this case, the egg problem still occurs. Sometimes the program really needs to index, especially when the index value is used as a parameter to the function called by the loop body. What should I do? Python also has a solution: enumerate (colors), which can return a pair of values: Index, variable, as shown below.

for i,d in enumerate([1, 2, 3, 4]):

The for of Python is also known as for-else. In a program, there is often a scenario where a linked list is traversed cyclically. If you find the desired member, the position of the Member is immediately returned. Otherwise, all elements must be searched.

ages = [42, 21, 18, 33, 19]are_all_adult = Truefor age in ages:    if age < 18:        are_all_adult = False        breakif are_all_adult:    print 'All are adults!'

If it is a C language, this is good. But in Python's view, this is also a pain point, because it can be like this:

ages = [42, 21, 18, 33, 19]for age in ages:    if age < 18:        breakelse    print 'All are adults!'

When the break in the loop is not executed, the last loop will be executed in the else. The egg-sore people also name it an egg-sore, the more appropriate statement is un-break.
Of course, Python has another way to implement this function, which requires only two lines of code, which will be mentioned later.

Dictionary

The previous section describes common list loops. Python comes with a unique data type: dictionary loop. The value of a variable is only a dictionary key value but has no content:

for key in groups:   print key, '--->', groups[key]

When you see the groups [key], the egg pain hits again. Yes, the dictionary loop in Python should not look like this. It is designed like this:

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

Yes, that's what you see. The key value and the entry content are returned in pairs. This also has an additional benefit: When the dictionary becomes very large, items () changing to interitems () can effectively improve Python performance and save memory. This is called an iterator, which will be mentioned later.

When talking about the dictionary, pay attention to the following code:

groups = {}    ...    if name not in groups:        groups[name] = []    groups[name].append(person)

This is a typical Python code written by a C programmer. It not only has an egg groups [name], but also has multiple levels of indentation, judgment, and empty assignment lists. It is simply an egg pain plus three levels. According to the Law of egg pain, some people with egg pain must help solve this problem:

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

Or

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

The dictionary groups automatically calls the function list to create an empty list only when the name is used as the key value for the first time. If the name already exists, the append action of the list is called directly. Xiaobian prefers the second method, and the code is more concise and clear during insertion. What do you think?groups = {}Is defining variables, egg pain... ...

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.