Several things you should pay attention to when coding Python

Source: Internet
Author: User

In the programming process, you can learn more about the language and some skills, which can make you a good programmer.

For Python programmers, pay attention to these things mentioned in this article. You can also take a look at the Zen of PythonPython Zen). Some precautions are mentioned here and examples are provided to help you quickly improve your performance.

1. Beauty is better than ugliness

Implement a function: Read a column of data, return only an even number, and divide it by 2. Which of the following code is better?

 
 
  1. #----------------------------------------    
  2.   halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums))  
  3.     
  4. #----------------------------------------    
  5.     
  6.   def halve_evens_only(nums):  
  7.       return [i/2 for i in nums if not i % 2] 

2. Remember the simple things in Python

 
 
  1. # Swap two variables
  2.  
  3. A, B = B,
  4.  
  5. # Slice) the step parameter in the operator. The prototype of the slice operator in python is [start: stop: step], that is, [start index: End index: step value]).
  6.  
  7. A = [1, 2, 3, 4, 5]
  8. >>> A [: 2] # traverse the incremental data of 2 in the list
  9. [1, 3, 5]
  10.  
  11. # In special cases, 'x [:-1] 'is a practical method for implementing the reverse order of x.
  12.  
  13. >>> A [:-1]
  14. [5, 4, 3, 2, 1]
  15.  
  16. # Reverse partitioning
  17.  
  18. >>> X [:-1]
  19. [5, 4, 3, 2, 1]
  20.  
  21. >>> X [:-2]
  22. [5, 3, 1]

3. Do not use a mutable object as the default value.

 
 
  1. Def function (x, l = []): # Do not do this
  2.  
  3. Def function (x, l = None): # Good Method
  4. If l is None:
  5. L = []

This is because when the def declaration is executed, the default parameter is always evaluated.

4. Use iteritems instead of items

Iteritems uses generators, so iteritems is better when iteration is performed through a very large list.

 
 
  1. D = {1: "1", 2: "2", 3: "3 "}
  2.  
  3. For key, val in d. items () # build a complete list when calling
  4.  
  5. For key, val in d. iteritems () # Only call the value when a request is made

5. Use isinstance instead of type

 
 
  1. # Do not do this
  2.  
  3. If type (s) = type (""):...
  4. If type (seq) = list or \
  5. Type (seq) = tuple :...
  6.  
  7. # This should be the case
  8.  
  9. If isinstance (s, basestring ):...
  10. If isinstance (seq, (list, tuple )):...

For the reason, see stackoverflow.

Note that I use basestring instead of str, because if a unicode object is a string, I may try to check it. For example:

 
 
  1. >>> a=u'aaaa' 
  2. >>> print isinstance(a, basestring)  
  3. True 
  4. >>> print isinstance(a, str)  
  5. False 

This is because in Python 3.0 and earlier versions, there are two string types: str and unicode.

6. understand various containers

Python has various container data types. In specific cases, this is a better choice than built-in containers such as list and dict.

I'm sure most people don't use it. Some careless people around me may write code in the following ways.

 
 
  1. freqs = {}  
  2. for c in "abracadabra":  
  3.     try:  
  4.         freqs[c] += 1 
  5.     except:  
  6.         freqs[c] = 1 

Some people may say that the following is a better solution:

 
 
  1. freqs = {}  
  2. for c in "abracadabra":  
  3.     freqs[c] = freqs.get(c, 0) + 1 

More specifically, the collection ultdict collection type should be used.

 
 
  1. from collections import defaultdict  
  2. freqs = defaultdict(int)  
  3. for c in "abracadabra":  
  4.     freqs[c] += 1 

Other containers:

 
 
  1. Namedtuple () # factory function, used to create a subclass of tuples with named Fields
  2. Deque # A list-like container that allows arbitrary terminals to quickly append and retrieve
  3. Counter # dict subclass for counting hash objects
  4. OrderedDict # dict subclass, used to store the added command records
  5. Defaultdict # dict subclass, used to call factory functions to supplement Missing Values

7. magic method of creating classes in Python magic methods)

 
 
  1. _ Eq _ (self, other) # define = Operator Behavior
  2. _ Ne _ (self, other) # definition! = Operator Behavior
  3. _ Lt _ (self, other) # defines the behavior of the <Operator
  4. _ Gt _ (self, other) # define> operator behavior
  5. _ Le _ (self, other) # defines the behavior of the <= Operator
  6. _ Ge _ (self, other) # define> = Operator Behavior

8. If necessary, use the Ellipsis "...")

Ellipsis is used to segment high-dimensional data structures. As slice: insert to extend the multi-dimensional slice to all dimensions. For example:

 
 
  1. >>> From numpy import arange
  2. >>> A = arange (16). reshape (2, 2, 2)
  3.  
  4. # Now, we have a four-dimensional Matrix 2x2x2x2. If you select all the first elements in the four-dimensional matrix, you can use the ellipsis symbol.
  5.  
  6. >>> A [..., 0]. flatten ()
  7. Array ([0, 2, 4, 6, 8, 10, 12, 14])
  8.  
  9. # This is equivalent
  10.  
  11. >>> A [:, 0]. flatten ()
  12. Array ([0, 2, 4, 6, 8, 10, 12, 14])

A FEW THINGS TO REMEMBER WHILE CODING IN PYTHON

From: http://www.iteye.com/news/25125

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.