Learning the cultural essence of a language can make you a better person.ProgramIf you have not read the Zen of Python, open the python command prompt and enter import this, you can find an example here for each item in the list.
- (Credit: itswater)
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=LambdaNums: 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:
- 1,BB= B,
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, 2, 3, 4, 5]
- >>>A [: 2] # incrementally iterate the entire list object using step 2
- [1, 3, 5]
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= []
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 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'Aaa'
- >>>Print isinstance (A, basestring)
- True
- >>>Print isinstance (A, STR)
- False
In python, versions earlier than 3.0 have two string types: Str and Unicode.
Object
|
Basestring
/\
STR 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 t:
- 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 defaultdict
- Freqs=Defaultdict(INT)
- For C in "abracadabra ":
- Freqs [c] + = 1
Other sets
- Namedtuple () # Use the specified domain to create the factory function of the metagroup subclass
- Deque # Quickly append and delete a list-like container at both ends of the sequence
- Counter # Calculate the dict subclass of the hash table
- Ordereddict # dict subclass that records the order of adding entities
- 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 behaviors of unequal operations ,! =.
- _ LT _ (self, other) # defines actions smaller than the operation,<.
- _ GT _ (self, other) # defines actions not greater than the operation,>.
- _ Le _ (self, other) # defines actions that are less than or equal to an operation,<=.
- _ Ge _ (self, other) # defines actions greater than or equal to an operation,>=.
Conditional assignment
- X=3If (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=3If (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 ifY= 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 ifY= 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]
Satyajit ranjeev
Translated by: bole online