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?
- #----------------------------------------
- halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums))
-
- #----------------------------------------
-
- def halve_evens_only(nums):
- return [i/2 for i in nums if not i % 2]
2. Remember the simple things in Python
- # Swap two variables
-
- A, B = B,
-
- # 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]).
-
- A = [1, 2, 3, 4, 5]
- >>> A [: 2] # traverse the incremental data of 2 in the list
- [1, 3, 5]
-
- # In special cases, 'x [:-1] 'is a practical method for implementing the reverse order of x.
-
- >>> A [:-1]
- [5, 4, 3, 2, 1]
-
- # Reverse partitioning
-
- >>> X [:-1]
- [5, 4, 3, 2, 1]
-
- >>> X [:-2]
- [5, 3, 1]
3. Do not use a mutable object as the default value.
- Def function (x, l = []): # Do not do this
-
- Def function (x, l = None): # Good Method
- If l is None:
- 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.
- D = {1: "1", 2: "2", 3: "3 "}
-
- For key, val in d. items () # build a complete list when calling
-
- For key, val in d. iteritems () # Only call the value when a request is made
5. Use isinstance instead of type
- # Do not do this
-
- If type (s) = type (""):...
- If type (seq) = list or \
- Type (seq) = tuple :...
-
- # This should be the case
-
- If isinstance (s, basestring ):...
- 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:
- >>> a=u'aaaa'
- >>> print isinstance(a, basestring)
- True
- >>> print isinstance(a, str)
- 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.
- freqs = {}
- for c in "abracadabra":
- try:
- freqs[c] += 1
- except:
- freqs[c] = 1
Some people may say that the following is a better solution:
- freqs = {}
- for c in "abracadabra":
- freqs[c] = freqs.get(c, 0) + 1
More specifically, the collection ultdict collection type should be used.
- from collections import defaultdict
- freqs = defaultdict(int)
- for c in "abracadabra":
- freqs[c] += 1
Other containers:
- Namedtuple () # factory function, used to create a subclass of tuples with named Fields
- Deque # A list-like container that allows arbitrary terminals to quickly append and retrieve
- Counter # dict subclass for counting hash objects
- OrderedDict # dict subclass, used to store the added command records
- Defaultdict # dict subclass, used to call factory functions to supplement Missing Values
7. magic method of creating classes in Python magic methods)
- _ Eq _ (self, other) # define = Operator Behavior
- _ Ne _ (self, other) # definition! = Operator Behavior
- _ Lt _ (self, other) # defines the behavior of the <Operator
- _ Gt _ (self, other) # define> operator behavior
- _ Le _ (self, other) # defines the behavior of the <= Operator
- _ 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:
- >>> From numpy import arange
- >>> A = arange (16). reshape (2, 2, 2)
-
- # 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.
-
- >>> A [..., 0]. flatten ()
- Array ([0, 2, 4, 6, 8, 10, 12, 14])
-
- # This is equivalent
-
- >>> A [:, 0]. flatten ()
- 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