Some Python idioms and tips: pythonic

Source: Internet
Author: User

Pythonic is actually a vague meaning, there is no definite explanation. There is not much on the internet about pythonic, my personal understanding is more python, more in line with Python's behavioral habits. This article is mainly to illustrate some of the python idioms and tricks, in fact, and the previous code code is similar to the good, are to increase the readability of code, but Pythonic may also be considered from the perspective of performance.

First of all, there are two Python features that have to be said list comprehension and generator Expression, a very streamlined syntax that largely replaces the lengthy for loop.

1. List comprehension lists comprehension is added in the Python2.0 version, is a more efficient, concise for structural substitutes, as the new handwriting on a few after it put it down, exclaimed too useful.

Example: assigning all elements in the original list to a new list after some action.

If you use a for loop, the code is as follows:

Oldlist = []

For item in Oldlist:

Newlist.append (func (item))

If you use list comprehension, the code is as follows:

NewList = [Func (item) for item in Oldlist]

We clearly see the difference, 3 lines, the Code readability Enhancement, and performance also improved a lot, it is said that basically can achieve the speed of C language.

The list comprehension also supports filtering, which is useful for applying a for IF clause in the process of generating lists. Examples are as follows:

Evens = [even for even in range] if even% 2 = = 0]

With just one line, you'll get all the even numbers from 0 to 9, filtering out the odd number.

2. Generator expressions (Generator expression): Generator expression is introduced in Python2.4. It's functionally similar to list comprehension, which you're going to ask, why join this. Because generator expression is more efficient, it avoids generating an entire list, improving performance and memory footprint, instead returning a generator object that iterates through each value in the returned list.

and the use of generator expression is simple, that is, the list comprehension in the brackets [] into parentheses (), the example is as follows:

NewList = (func (item) for item in oldlist)

The returned newlist is not actually a list, but rather the generator object mentioned earlier, which can be understood as an iterator to the list, similar to ITER in C + +. Each item in the list can be obtained through the Newlist.next () iteration.

List comprehension and generator expression is really the highlight of Python, concise and efficient, must often use, always use, seconds seconds.

Then there are a few tricks (most of the programming practices advocated in many languages):

1. String concatenation: Use ". Join for string concatenation instead of a + = B form." Because join will ensure that the time complexity of the process is linear and more efficient. Truth many people know, but most people still like to use "+", because this is too concise. In fact, many languages provide a way to splice strings or the corresponding classes, good programming habits from the beginning of the stitching string.

2. Exception type: Class-based exceptions are always better than string-based exceptions. We'd better construct a subclass based on exception.

When throwing an exception, use "Raise ValueError (' message ')" instead of "raise ValueError, ' message '" in the form.

3. None Judgment: When judging whether an instance variable is empty, you should always use ' is ' or ' is not ' instead of an equality operator.

4. Object type judgment: The comparison of object types should always replace the direct comparison type with isinstance (). For example:

Use if isinstance (obj, int): Instead of if Type (obj) is type (1):

5. String prefix judgment: avoid slicing strings when checking prefixes or suffixes. Replace them with StartsWith () and EndsWith () because they are clear and have fewer errors. For example:

Use if Foo.startswith (' Bar '): replace if foo[:3] = = ' Bar ':

6. Variable Value exchange: In other languages, we often exchange the values of two variables in this way. T=a; A=b; b=t;

But in Python, we have an easy way, A, B = B, A, and it's faster and cooler.

[Reprint] Www.cr173.com/html/8108_1.html

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.