1. Beauty is better than ugliness
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 #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 = []
4. Use items instead of items
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)): ...
>>> a=u'aaaa' >>> print isinstance(a, basestring) True >>> print isinstance(a, str) False
6. Understand various containers
freqs = {} for c in "abracadabra": try: freqs[c] += 1 except: freqs[c] = 1
freqs = {} for c in "abracadabra": freqs[c] = freqs.get(c, 0) + 1
from collections import defaultdict freqs = defaultdict(int) for c in "abracadabra": freqs[c] += 1
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
>>> 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])