Some suggestions for Python programming in "Zen of Python", Zen of python
Learning the cultural essence of a language can make you a better programmer. If you have not read the Zen of Python, open the Python command prompt and enter import this. You can find the corresponding example for each item in the list.
One thing that attracts my attention is:
Elegance is better than ugliness (Beautiful is better than uugly)
Take the following example:
The function of a list function with numeric parameters is to return the odd values in the return parameters, which can be written separately:
#----------------------------------------------------------------------- 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]
Remember the simple things in Python
Exchange of two variables:
a, b = b, a
The steps of parameters in the slice operation, such:
A = [1, 2, 3, 4, 5] >>> a [: 2] # incrementally iterate the entire list object using step 2 [1, 3, 5]
A special example 'x [:-1] 'is used to reverse the practical Syntax of x.
>>> a[::-1] [5,4,3,2,1]
Do not use a mutable object as the default parameter value (Don't use mutable as defaults)
Def function (x, l = []): # Do not do this def function (x, l = None): # A better way if l is None: l = []
Use iteritems instead of items
Iteriterms uses generators, so this method is better when there is a large Iteration Sequence
D = {1: "1", 2: "2", 3: "3"} for key, val in d. items () # Call items () to construct a complete list object for key, val in d. iteritems () # A value is generated only once each request is made during iteration.
This scenario and range are similar to xrange.
Use isinstance instead of type
Do not do this:
if type(s) == type(""): ...if type(seq) == list or \ type(seq) == tuple: ...
It should be like this:
if isinstance(s, basestring): ...if isinstance(seq, (list, tuple)): ...
As for why, see here: http://stackoverflow.com/a/1549854/504262
It should be noted that basestring instead of str is used here because you may use a unicode object to check whether it is a string. For example:
>>> a=u'aaaa'>>> print isinstance(a, basestring)True>>> print isinstance(a, str)False
In Python, versions earlier than 3.0 have two string types: str and unicode.
Learn the varous collections)
Python has a variety of container data types. In specific cases, select the python built-in containers such as list and dict. Generally, it is used as follows:
freqs = {}for c in "abracadabra": try: freqs[c] += 1 except: freqs[c] = 1
A better solution is as follows:
freqs = {} for c in "abracadabra": freqs[c] = freqs.get(c, 0) + 1
A better choice of collection type defautdict:
from collections import defaultdictfreqs = defaultdict(int) for c in "abracadabra": freqs[c] += 1
Other sets
Namedtuple () # Use the specified domain to create the factory function deque of the metagroup subclass # similar to the list container, fast append and delete Counter at both ends of the sequence # dict subclass of the statistics hash table OrderedDict # dict subclass that records the order of object addition defaultdict # Call the factory method to provide the default dict subclass for the key
Python magic method when creating a class:
_ Eq _ (self, other) # defines the behavior of equal operations, =. _ ne _ (self, other) # defines the behavior of unequal operations ,! =. _ Lt _ (self, other) # defines actions smaller than the operation, <. _ gt _ (self, other) # define actions not greater than the operation,>. _ le _ (self, other) # defines actions that are less than or equal to an operation, <=. _ ge _ (self, other) # define actions greater than or equal to the operation,> =.
Conditional assignment
x = 3 if (y == 1) else 2
The expression is just like: If y is equal to 1, 3 is assigned to x; otherwise, 2 is assigned to x. Of course, you can also use chained condition assignment if you have more complex conditions.
x = 3 if (y == 1) else 2 if (y == -1) else 1
However, when it comes to a specific point, it is a little too much.
Remember, you can use if-else In any expression, for example:
(func1 if y == 1 else func2)(arg1, arg2)
Func1 will be called if y is equal to 1, and func2 will be called. In both cases, the arg1 and arg2 parameters are included in the corresponding function.
Similarly, the following expression is also correct.
x = (class1 if y == 1 else class2)(arg1, arg2)
Class1 and class2 are two classes
Use Ellipsis when necessary
When creating a class, you can use _ getitem __to make your class work like a dictionary. Here is an example of this class:
class MyClass(object): def __init__(self, a, b, c, d): self.a, self.b, self.c, self.d = a, b, c, d def __getitem__(self, item): return getattr(self, item) x = MyClass(10, 12, 22, 14)
With _ getitem __, you can obtain the value of a through the x ['a'] of object x, which should be recognized as a fact.
This object is usually used to inherit the slicing (http://docs.python.org/library/stdtypes.html#bltin-ellipsis-object) of Python, if you add the following statement:
def __getitem__(self, item): if item is Ellipsis: return [self.a, self.b, self.c, self.d] else: return getattr(self, item)
We can use x […] The obtained sequence containing all items
>>> x = MyClass(11, 34, 23, 12)>>> x[...][11, 34, 23, 12]