Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.12 KB | None | 0 0
  1. # list of dict
  2. for i, movie in enumerate(sorted(a_list, key=lambda r: (r['rating'], r['year']), reverse=True)):
  3. if i >= 4: break
  4. print(str(i) + " "),
  5. pretty(movie)
  6.  
  7. from operator import itemgetter
  8. m_list = sorted(a_list, key=itemgetter('rating','year'))
  9.  
  10. rows.sort(key=itemgetter('rating'))
  11. for date, items in itertools.groupby(rows, keys=itemgetter('date')):
  12. print(date) ; for i in items: print(' ', i)
  13.  
  14. data = [1,2,3,4] ; name, shares, price, date = data ; name
  15. first, *middle, last = grades ; return avg(middle)
  16. record = ('Sean', 's@tg.com', '818-406-0674', '650-436-8471')
  17. name, email, *phone = record
  18.  
  19. import heapq
  20. nums = [1,2,3,4,4,5]
  21. print(heapq.nlargest(3, nums)) ; print(heapq.nsmallest(3, nums))
  22. # list of dict
  23. cheap_list = heapq.nsmallest(3, a_list, key=lambda s: s['price'])
  24.  
  25. # dict keys in common, in a not b, k,v pairs in common
  26. a.keys() & b.keys() # { 'x', 'y' }
  27. a.keys() - b.keys() # { 'z' }
  28. a.items() & b.items() # { 'y', 2 }
  29. # remove some keys into new dict
  30. c = {key:a[key] for key in a.keys() - { 'z', 'w' }}
  31.  
  32. [n for n in a_list if n > 0]
  33. pos = (n for n in a_list if n > 0)
  34. for x in pos: print(x)
  35.  
  36. def is_int(val):
  37. try:
  38. x = int(val)
  39. return True
  40. except ValueError:
  41. return False
  42. ivals = list(filter(is_int, values))
  43.  
  44. p1 = { key:value for key, value in prices.items() if value > 200 }
  45.  
  46. if any(name.endswith('.py') for name in files): print('yes')
  47.  
  48. s = sum(x * x for x in nums)
  49.  
  50. 'aljfkjkldjfklj'.replace('a', 'b')
  51. 'abc'.ljust(20).rjust(20).center(20)
  52. '{:<10s} {:>20s} {:10.2f}'.format(a, b, c)
  53. '{:0,.1f}'.format(1234.56789) # 1,234.6
  54. round(1.23, 1) # 1.2
  55. round(1.27, 1) # 1.3
  56. round(1.25361, 3) # 1.254
  57. round(1627731, -1) # 1627730
  58.  
  59. int has bin(), oct() and hex()
  60.  
  61. random.choice([])
  62. random.sample([], 3)
  63. random.shuffle([])
  64. random.randint(0,10)
  65. random.random() # float between 0 and 1
  66. random.getrandbits(200) # int returned with 200 random bits
  67.  
  68. with open('/etc/passwd') as f:
  69. try:
  70. while True:
  71. line = next(f) ; print(line, end='')
  72. except StopIteration:
  73. pass
  74.  
  75. reversed([])
  76.  
  77. for p in itertools.permutations(['a','b','c']): print(p) # ('a','b','c')\n('b','c','a')
  78.  
  79. with open('file', 'rt', encoding='ascii', errors='ignore') as f:
  80. data = f.read() or for line in f:
  81.  
  82. # file write mode 'x' will FileExistsError if file exists
  83.  
  84. with open('a.csv') as f:
  85. f_csv = csv.reader(f, delimiter='\t')
  86. headers = next(f_csv)
  87. for row in f_csv: print(row)
  88.  
  89. with fileinput.input('/etc/passwd') as f:
  90. for line in f: print(line, end='')
  91.  
  92. def is_valid(address):
  93. try:
  94. socket.inet_aton(address)
  95. except socket.error:
  96. return False
  97. return True
  98.  
  99. funcs = [a_func]
  100. funcs[0](2, 3)
  101. func_dict = {
  102. 'cond_a': handle_a,
  103. 'cond_b': handde_b
  104. }
  105. func_dict.get(cond, handle_default)()
  106. def disp_dict(operator, x, y):
  107. return {
  108. 'add': lambda: x + y,
  109. 'sub': lambda: x - y
  110. }.get(operator, lambda: None)()
  111.  
  112. s.issubset(t) # every s element in t
  113. s.issuperset(t) # every t in s
  114. s.union(t) # new set with s and t elements
  115. s.intersection(t) # new set with common s and t
  116. s.symmetric_difference(t) # new set with elements of s and t not in both
  117. s.remove(x) # KeyError if not present
  118. s.discard(x) # remove if exists
  119. s.pop() # KeyError if empty
  120. s.clear() # wipe out set
  121.  
  122. del(a_dict[key])
  123.  
  124. list.append / extend / insert(i,x) / remove(x) / pop(i) / clear() (del a[:]) / count(x) / sort(key=None, reverse=False) / reverse() / copy()
  125.  
  126. # lambda 1-line function
  127. # no def nor return keywords (implicit)
  128.  
  129. lambda x: x * 2
  130. def double(x):
  131. return x * 2
  132.  
  133. lambda x, y: x + y
  134. def add(x, y):
  135. return x + y
  136.  
  137. mx = lambda x, y: x if x > y else y
  138. def mx(x, y):
  139. if x > y:
  140. return x
  141. else:
  142. return y
  143. print(mx(8, 5))
  144.  
  145. # map runs function against each element of a list
  146. # returns the modified list
  147. # [m, n, p] mapped with f() -> [f(m), f(n), f(p)]
  148. n = [4, 3, 2, 1]
  149. print(list(map(lambda x: x**2, n)))
  150. # map(function, list)
  151. # print(list(map(square, n))) for square()
  152. print([x**2 for x in n])
  153.  
  154. # filter filters items from a list
  155. # returns list
  156. n = [4, 3, 2, 1]
  157. print(list(filter(lambda x: x > 2, n)))
  158. print([x for x in n if x > 2])
  159.  
  160. # reduce runs function against every pair of elements in a list
  161. # multiple a bunch of numbers together
  162. def mult(lst1):
  163. prod = lst1[0]
  164. for i in range(1, len(lst1)):
  165. prod *= lst1[i]
  166. return prod
  167. n = [4, 3, 2, 1]
  168. print(reduce(lambda x, y: x * y, n))
  169.  
  170. # Generators
  171. def sq_nums(nums):
  172. result = []
  173. for i in nums:
  174. result.append(i*i)
  175. return result
  176. my_nums = sq_nums([1, 2, 3, 4, 5])
  177. def sq_nums_2(nums):
  178. for i in nums:
  179. yield(i*i)
  180. my_nums = sq_nums_2([1, 2, 3, 4, 5])
  181. # that returns a generator object
  182. # does not hold all results in memory
  183. print next(my_nums)
  184. print next(my_nums)
  185. # StopIteration error if next cannot pull another result
  186. for num in my_nums:
  187. print(num)
  188. # no exception
  189. my_nums = [x*x for x in [1, 2, 3, 4, 5]]
  190. my_nums = (x*x for x in [1,2,3,4,5])
  191. print(list(my_nums))
  192.  
  193. mem_profile.memory_usage_resource()
  194. t1 = time.clock()
  195. run this
  196. t2 = time.clock()
  197. "{} s".format(t2-t1)
  198.  
  199. my_list = [n for n in nums]
  200.  
  201. my_list = filter(lambda n: n%2 == 0, nums)
  202.  
  203. my_dict = {name: hero for name, hero in zip(names, heros) if name != 'Peter'}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement