A few things to note when coding Python

  • 2020-04-02 09:52:13
  • OfStack

In the process of programming, knowing more about the language around some knowledge, and some skills, can let you speed up to become a good programmer.
For Python programmers, you need to be aware of these things. You can also take a look at Zen of Python, which includes some notes and examples to help you improve quickly.

1. Beauty is better than ugliness

Implement a function: read a column of data, return only an even number and divide by 2. Which of the following 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 very simple things in Python


#  Swap two variables 
a, b = b, a
#  Slice ( slice ) operator step Parameters. The slice operator is in python The prototype is [start:stop:step] , that is: [ The starting index : The ending index : Step length value ] ) 
a = [1,2,3,4,5]
>>> a[::2] #  The increment in the traversal list is 2 The data of 
[1,3,5]
#  In special cases, `x[::-1]` Is to realize the x Practical way to reverse order 
>>> a[::-1]  
[5,4,3,2,1]
#  Reverse and slice 
>>> x[::-1]
[5, 4, 3, 2, 1]
>>> x[::-2]
[5, 3, 1]

3. Don't use mutable objects as default values


def function(x, l=[]): # Don't be so 

def function(x, l=None): #  A good way 
   if l is None:
      l = []

This is because the default parameters are always evaluated when the def declaration is executed.

4. Use iteritems instead of items


iteritems  use generators  , so when iterating over a very large list, iteritems  Better. 
d = {1: "1", 2: "2", 3: "3"}
for key, val in d.items() #  Build the complete list when invoked 
for key, val in d.iteritems() #  Only values are invoked when requested 

5. Use isinstance instead of type


#  Don't do that          
if type(s) == type(""): ...
if type(seq) == list or 
   type(seq) == tuple: ...

#  Should be like this 
if isinstance(s, basestring): ...
if isinstance(seq, (list, tuple)): ...

See stackoverflow for the reason

Notice that I'm using basestring instead of STR, because if a unicode object is a string, you might try to check it. Such as:


>>> a=u'aaaa'
>>> print isinstance(a, basestring)
    True
>>> print isinstance(a, str)
    False

This is because in Python 3.0 and later, there are two string types, STR and unicode.

Learn about containers

Python has a variety of container data types, which are a better choice in certain situations than built-in containers (such as list and dict).

I'm sure most people don't use it. Some of the careless people around me, some of them might write code in the following way.


freqs = {}
for c in "abracadabra":
    try:
        freqs[c] += 1
    except:
        freqs[c] = 1

Others would argue that the following is a better solution:

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

More specifically, the collection type defaultdict should be used.

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

Other containers:
Namedtuple ()       The # factory function to create a subclass of tuples with named fields  
A deque                     A list-like container that allows arbitrary ends to be quickly attached and fetched  
Counter     # dict subclass for hash object counting  
OrderedDict     # dict subclass to store added command records  
defaultdict     # dict subclass to call the factory function to supplement the missing value

7. Magic methods for creating classes in Python

      __eq__ (self, other)           # defines the behavior of the == operator  
      __ne__ (self, other)           # define! The behavior of the = operator  
      __lt__ (self, other)           # define < The behavior of the operator  
      __gt__ (self, other)           # define > The behavior of the operator  
      __le__ (self, other)           # define < The behavior of the = operator  
      __ge__ (self, other)           # define > The behavior of the = operator

Use Ellipsis ("... ") when necessary. )

Ellipsis is used to slice through high-dimensional data structures. Inserts as slices (:) to extend multidimensional slices to all dimensions. Such as:


>>> from numpy import arange
    >>> a = arange(16).reshape(2,2,2,2)

    #  Now, we have one 4 D matrix 2x2x2x2 , if you choose 4 All the first elements in the dimension matrix, you can use ellipsis Symbols. 

    >>> a[..., 0].flatten()
    array([ 0, 2, 4, 6, 8, 10, 12, 14])

    #  This is equivalent to 
    >>> a[:,:,:,0].flatten()
    array([ 0, 2, 4, 6, 8, 10, 12, 14])


Related articles: