Learning its cultural essence around a language can make you a better programmer. If you haven't read Python Zen (Zen of Python), open the Python command prompt and enter import this, and you can find the corresponding example here for each item in the list.
One of the lines that caught my attention was:
Elegance is better than ugliness (beautiful is better than ugly)
Look at the following example:
A list function with a numeric parameter whose function is to return an odd number of arguments to write 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 to I in nums if not I% 2]
Remember the very simple things in Python
Exchange of two variables:
The steps of a parameter in a slice operation, such as:
A = [1,2,3,4,5]
>>> A[::2] # Iterate over the entire list object in increments of 2
[1,3,5]
A special example of ' x[::-1] ' is used to reverse the practical syntax of X.
Do not use a Mutable object as the default parameter value (don ' t using mutable as defaults)
def function (x, l=[]): # Don't do this
. def function (x, L=none): # Better one way
if L is None:
l = []
Use Iteritems rather than items
Iteriterms is using generators, so when iterating a large sequence is this method better
D = {1: "1", 2: "2", 3: "3"}
for Key, Val in D.items () # calls items () to build a complete list object for
key, Val in D.iterite MS () # Generates a value only once per request at iteration
This scenario and range have a similar relationship to xrange.
Using isinstance rather than type
Don't 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 do this, look here: http://stackoverflow.com/a/1549854/504262
Note that the use of basestring instead of STR is because you might use a Unicode object to check for string, for example:
>>> a=u ' aaaa '
>>> print isinstance (A, basestring)
True
>>> print isinstance ( A, str)
False
Because there are two types of string type str and Unicode in Python under 3.0
Learn all kinds of collections (learn the various collections)
Python has a wide variety of container data types, and in certain cases it chooses Python-built containers such as list and Dict. More often than not, you use the following methods:
Freqs = {} for
C in ' Abracadabra ':
try:
freqs[c] + = 1
except:
freqs[c] = 1
A better scenario is as follows:
Freqs = {}
for C in "Abracadabra":
freqs[c] = Freqs.get (c, 0) + 1
A better Choice collection type defautdict:
From collections import defaultdict
freqs = defaultdict (int) to
C in "Abracadabra":
freqs[c] = 1
Other collections
Namedtuple () # Creates a factory function of a tuple subclass with the specified domain
deque # Similar to list container, fast append and delete at both ends of the sequence
Counter # Statistical hash Table Dict Subclass
ordereddict # Record entity Add Order Dict subclass
Defaultdict # Call the Factory method Dict subclass that provides default values for key
Python's Magic method when creating classes:
__eq__ (self, Other) # defines the behavior of equality operations, = =.
__ne__ (self, Other) # defines the behavior of unequal operations,!=.
__lt__ (self, other) #定义小于操作的行为.
__gt__ (self, other) #定义不大于操作的行为.
__le__ (self, other) #定义小于等于操作的行为, <=.
__ge__ (self, other) #定义大于等于操作的行为, >=.
Conditional assignment
x = 3 if (y = = 1) Else 2
The expression is just like this: if Y equals 1, assign 3 to X, or assign 2 to X, you can also use chained conditions to assign values if you have more complicated conditions.
x = 3 if (y = = 1) Else 2 if (y = = 1) Else 1
However, at a certain point, it is a bit excessive.
Remember, you can use If-else in any expression such as:
(func1 if y = = 1 else func2) (Arg1, arg2)
FUNC1 will be called if Y equals 1, otherwise func2 is invoked. In both cases, the arg1 and arg2 two 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 get your class to work like a dictionary, take the following class for example:
Class MyClass (object):
def __init__ (self, A, B, C, D):
self.a, self.b, SELF.C, self.d = A, B, C, D
def __getit Em__ (self, item): Return
getattr (self, item)
x = MyClass (10, 12, 22, 14)
Because of the __getitem__, you can get the value of a by the x[' a ' of object X, which should be a recognized fact.
This object is typically used to inherit python slices (slicing) (Http://docs.python.org/library/stdtypes.html#bltin-ellipsis-object) 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[...] Gets the sequence that contains all the items
>>> x = MyClass (one, one,)
>>> x[...]
[11, 34, 23, 12]