Advertisement
rfmonk

idiomatic.py

Dec 12th, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.46 KB | None | 0 0
  1. ''' from Transforming Code into Beautiful, Idiomatic Python
  2. by Raymond Hettinger'''
  3.  
  4. for i in [0, 1, 2, 3, 4, 5]:
  5.     print i**2
  6.  
  7. for i in range(6):
  8.     print i**2
  9.  
  10. for i in xrange(6):
  11.     print i**2
  12.  
  13. colors = ['red', 'green', 'blue', 'yellow']
  14.  
  15. # don't do this
  16. for i in range (len(colors)):
  17.     print colors[i]
  18.  
  19. # do this
  20. for color in colors:
  21.     print color
  22.  
  23. # don't
  24. for i in range(len(colors) -1, -1, -1):
  25.     print colors[i]
  26.  
  27. # do
  28. for color in reversed(colors):
  29.     print color
  30.  
  31. # don't
  32. for i in range(len(colors)):
  33.     print i, '-->' colors[i]
  34.  
  35. # do
  36. for i, color in enumerate(colors):
  37.     print i, '-->', colors[i]
  38.  
  39. ''' Looping over two collections '''
  40. names = ['raymond', 'rachel', 'matthew']
  41. colors = ['red', 'green', 'blue', 'yellow']
  42.  
  43. # don't
  44. n = min(len(names), len(colors))
  45. for i in range(n):
  46.     print names[i], '-->', colors[i]
  47.  
  48. # don't
  49. for name, color in zip(names, colors):
  50.     print name, '-->', color
  51.  
  52. # do
  53. for name, color in izip(names, colors):
  54.     print name, '-->', color
  55.  
  56. ''' Looping in sorted order '''
  57. colors = ['red', 'green', 'blue', 'yellow']
  58.  
  59. for color in sorted(colors):
  60.     print color
  61.  
  62. for color in sorted(colors, reverse=True):
  63.     print color
  64.  
  65. def compare_length(c1, c2):
  66.     if len(c1) < len(c2): return -1
  67.     if len(c1) > len(c2): return 1
  68.     return 0
  69.  
  70. # don't
  71. print sorted(colors, cmp=compare_length)
  72.  
  73. # do
  74. print sorted(colors, key=len)
  75.  
  76. # Call a function until a sentinel value
  77.  
  78. blocks = []
  79. while True:
  80.     block = f.read(32)
  81.     if block == '':
  82.         break
  83.     blocks.append(block)
  84.  
  85. blocks = []
  86. for block in iter(partial(f.read, 32), ''):
  87.     blocks.append(block)
  88.  
  89. # Distinguishing mulitiple exit points in loops
  90. def find(seq, target):
  91.     found = False
  92.     for i, value in enumerate(seq):
  93.         if value == tgt:
  94.             found = True
  95.             break
  96.     if not found:
  97.         return -1
  98.     return i
  99.  
  100. def find(seq, target):
  101.     for i, value in enumerate(seq):
  102.         if value == tgt:
  103.             break
  104.     else:
  105.         return -1
  106.     return i
  107.  
  108. '''Dictionary Skills
  109. * Mastering dictionaries is a fundamental Python Skill
  110. * They are the fundamental tool for expressing relationships,
  111.     linking, counting, and grouping.    '''
  112.  
  113. # Looping over the dictionary keys
  114. d = ('matthew': 'blue', 'rachel': 'green', 'raymond': 'red')
  115.  
  116. for k in d:
  117.     print k
  118.  
  119. for k in d.keys():
  120.     if k.startswith('r'):
  121.         del d[k]
  122.  
  123. # Looping over a dictionary keys and values
  124.  
  125. for k in d:
  126.     print k, '-->', d[k]
  127.  
  128. for k, v in d.items():
  129.     print k, '-->', v
  130. #====================================
  131. # Construct a dictionary from pairs
  132.  
  133. names = ['raymond', 'rachel', 'matthew']
  134. colors = ['red', 'green', 'blue']
  135.  
  136. d = dict(izip(names, colors))
  137. ('matthew': 'blue', 'rachel': 'green', 'raymond': 'red')
  138.  
  139. # Counting with dictionaries
  140.  
  141. colors = ['red', 'green', 'red', 'blue', 'green', 'red']
  142.  
  143. d = {}
  144. for color in colors:
  145.     if color not in d:
  146.         d[color] = 0
  147.     d[color] += 1
  148.  
  149. {'blue':1, 'green':2, 'red':3}
  150.  
  151. # simplified
  152. d = {}
  153. for color in colors:
  154.     d[color] = d.get(color, 0) + 1
  155.  
  156. d = defaultdict(int)
  157. for color in colors:
  158.     d[color] += 1
  159.  
  160.  
  161. ### Grouping with dictionaries -- Part I
  162. names = ['raymond', 'rachel', 'matthew', 'roger',
  163.          'betty', 'melissa', 'judith', 'charlie']
  164.  
  165. d = {}
  166. for name in names:
  167.     key = len(name)
  168.     if key not in d:
  169.         d[key] = []
  170.     d[key].append(name)
  171.  
  172. # Grouping with dictionaries == Part II
  173.  
  174. d = {}
  175. for name in names:
  176.     key = len(name)
  177.     d.setdefault(key, []).append(name)
  178.  
  179. d = defaultdict(list)
  180. for name in names:
  181.     key = len(name)
  182.     d[key].append(name)
  183.  
  184. """==================
  185. 28:00 minutes """
  186. # popitem
  187. # linking dictionaries
  188. # ChainMap
  189. # Improving Clarity
  190. # positional arguments and indicies
  191. twitter_search('@obama', retweets=False, numtweets=20, popular=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement