Several things to pay attention to when coding Python

original
2012/07/27 10:02
Reading number 795

In the process of programming, more knowledge about the language and some skills can help you become an excellent programmer.

For Python programmers, you need to pay attention to these things mentioned in this article. You can also have a look Zen of Python (Zen of Python), which mentioned some precautions, with examples, can help you improve quickly.

1. Beauty is better than ugliness

Realize a function: read a column of data, return only an even number and divide by 2. Which of the following codes is better?

 halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums))

VS

 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 #Step parameter in the slice operator. (The prototype of the slicing operator in python is [start: stop: step], that is, [start index: end index: step value]) a = [1,2,3,4,5] >>>A [:: 2] # Traverse data with increment of 2 in the list [1,3,5] #In special cases, 'x [:: - 1]' is a practical way to reverse the order of x >>> a[::-1] [5,4,3,2,1] #Reverse order and slice >>> x[::-1] [5, 4, 3, 2, 1] >>> x[::-2] [5, 3, 1]

3. Do not use mutable objects as default values

 Def function (x, l=[]): # Don't do this Def function (x, l=None): # Good way if l is None: l = []

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

4. Use items instead of items

Iterites uses generators, so when iterating through very large lists, iterites is better.

 d = {1: "1", 2: "2", 3: "3"} For key, val in d.items() # Build a complete list when calling For key, val in d.items() # Only call values when requesting

5. Use isinstance instead of 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)): ...

For reasons, 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 there are two string types str and unicode in Python versions below 3.0.

6. Understand various containers

Python has a variety of 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 way.

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

Others would say that the following is a better solution:

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

More specifically, you should use the collection type defaultdict.

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

Other containers:

 Namedtuple() # Factory function, used to create tuple subclasses with named fields Deque # List like container, allowing any end to quickly attach and retrieve Counter # dict subclass, used to count hash objects OrderedDict # Dict subclass, used to store the added command record Defaultdict # dict subclass, used to call factory functions to supplement missing values

7. Magic methods for creating classes in Python

 __Eq__ (self, other) # Define the behavior of the==operator __Ne__ (self, other) # Definition= Operator behavior __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

8. Use Ellipsis (ellipsis "...") if necessary

Ellipsis is used to slice high-dimensional data structures. Insert as a slice (:) to extend multidimensional slices to all dimensions. For example:

 >>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2) #Now, there is 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 to >>> a[:,:,:,0].flatten() array([ 0,  2,  4,  6,  8, 10, 12, 14])

Original text: a few things to remember while coding in python

Expand to read the full text
Loading
Click to join the discussion 🔥 (2) Post and join the discussion 🔥
Reward
two comment
twenty-five Collection
four fabulous
 Back to top
Top