Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.63 KB | None | 0 0
  1. 1 - ############ built-in zip function for i, j in zip(list1, list2)
  2.  
  3. 2 - ############ built-in enumerate function for i,j in enumerate(lista) i = indice j = element
  4.  
  5. 3 - ############ accessing a global variable a = 10 def foo(): global a a = 10
  6.  
  7. 4 - ########### range performance
  8.  
  9. Python 2.7
  10.  
  11. for i in range(100):
  12.  
  13. Bad Idea, range will be evaluate each loop iteration
  14.  
  15. a = range(100) for i in a:
  16.  
  17. Good Idea
  18.  
  19. or
  20.  
  21. for i in xrange(100)
  22.  
  23. xrange is a Yield
  24.  
  25. Python 3
  26.  
  27. range == xrange in Python 2.7
  28.  
  29. 5 - ########## avoiding Dictionaries KeyError dict.get(key, default) instead of dict[key]
  30.  
  31. 6 - ########## for else for i in xrange(10): pass else: # Else means, no brak pass
  32.  
  33. 7 - ########## try excepet else finally
  34.  
  35. Python 2.7
  36.  
  37. try: pass except Exception, e: raise else: # Else means no exception pass finally: # It will always execute pass
  38.  
  39. Python 3
  40.  
  41. try: 1/0 except (Exception, ZeroDivisionError) as e: print(e) else: print('No exception') finally: print('Finally')
  42.  
  43. 8 - ########## List comprehension m = [e for i in range(0, 10) for e in range(5) if ((e%2==0))] m = [(i,e) for i in range(0, 10) for e in range(5) if ((e%2==0))]
  44.  
  45. 9 - ########## String parameters Python print ("%d" % 10) print ("%d %s %.2f" % (10, 'Gp', 1.2)) print ("{name} {age}".format(name='Gp', age=28)) print ("%s %d".format('Gp', 28)) # Doesn't work lista = ['Gp', 28] print ("{0} {1}".format(*lista)) dic = {'name': 'Gp', 'age': 28} print ("{name} {age}".format(**dic)) nome = 'Gp' idade = 28 print('Ola, meu nome e %(nome)s, eu tenho %(idade)d anos.' % vars())
  46.  
  47. 10 - ######### Args and kwargs Python def f(args): # You use args when you don't know how many arguments might be passed print(type(args)) # list for i in args: print i
  48.  
  49. f([1,2,2]) t = (2,3,4,4) f(t) l = [3,3,3] f(l)
  50.  
  51. if you put * in the assinment parameters you should call the function puttin
  52.  
  53. def f2(**args): # **kwargs allows you to handle named arguments that you have not defined in advance print(type(args)) # print dict for name, value in args.iteritems(): print name, value
  54.  
  55. f2(key1=10, key2=20) f2({'g': 99, 'h':100}) # It doesn't work if you dont put **
  56.  
  57. 11 - ######### Operations Python 2.7
  58.  
  59. 10/3 = 3 10//3. = 3.0 # Doble slashes forces round down
  60.  
  61. Python 3 10/3 = 3.3333333 10//3. = 3.0 # Doble slashes forces round down
  62.  
  63. 12 - ######### Tuples vs Lists Tuple, Imutable, less memory Lists, Mutable, More memory
  64.  
  65. 13 - ########## Named parameters def f(a,b,c=10): print(a,b,c)
  66.  
  67. f(10,20,20) f(10,20) f(a=10, b=10) f(a=10, c=10) # it doesn't work
  68.  
  69. 14 - ########## Yeild def primeiros(n): i = 0 while i < n: yield i i += 1 else: yield 'Fim'
  70.  
  71. for i in primeiros(10): print i
  72.  
  73. 15 - ########## OO constructor class Doc(object): def init: self.name = 'rex'
  74.  
  75. 16 - ########## OO Inheritance class dog(object): def init(self): print 'Object instaciate'
  76.  
  77. def latir(self, ofthen):
  78. print 'Au! ' * ofthen
  79. class SaoBernardo(dog): def latir(self, ofthen = 1): print 'Woof! ' * ofthen
  80.  
  81. c = dog() c.latir(1)
  82.  
  83. d = SaoBernardo() d.latir(10)
  84.  
  85. Object instaciate Au! Object instaciate Woof! Woof! Woof! Woof! Woof! Woof! Woof! Woof! Woof! Woof!
  86.  
  87. 17 - ########## OO Super class SaoBernardo(dog): def latir(self, ofthen = 1): super(SaoBernardo, self).latir(ofthen=2)
  88.  
  89. 18 - ########## OO accessing private atributes myObj._ClassName__myPrivateMethod()
  90.  
  91. 19 - ########## property/getter, setter, deleter class C(object): def init(self): self._x = None
  92.  
  93. @property
  94. def getX(self):
  95. print 'Getter'
  96. return self._x
  97.  
  98. @getX.setter
  99. def setX(self, value):
  100. print 'Setter'
  101. self._x = value
  102.  
  103. @getX.deleter
  104. def delX(self):
  105. print 'Delete'
  106. del self._x
  107. 20 - ########## Iterators
  108.  
  109. 21 - ########## Generators
  110.  
  111. 22 - ########## Lambga m = [lambda x , i=i: (i * x) for i in range(3)] x pararameter i=i fixing i in each iteration (i*x) return
  112.  
  113. 23 - ########## Map n = [2,4,6,8] print map(lambda x: x**2, n) [4, 16, 36, 64]
  114.  
  115. Python 3 l = ['1', '2'] l = list(map(int, l))
  116.  
  117. 24 - ########## Reduce n = [2,3,4,5,6] print reduce(lambda x, y : x + y, n)
  118.  
  119. 20
  120.  
  121. 25 - ########## Filter
  122.  
  123. Filter just return True elements
  124.  
  125. n = [2,3,4,5,6,7,8,9,10] print filter(lambda x : x if x % 2 == 0 else None, n)
  126.  
  127. 26 - ########## Shallow copy and Deep Copy
  128.  
  129. 27 - ########## input input().strip() Remove spaces from the begining and ending of string inputed
  130.  
  131. 28 - ######## Threads #!/usr/bin/python
  132.  
  133. import thread import time
  134.  
  135. Define a function for the thread
  136.  
  137. def print_time( threadName, delay):
  138.  
  139. count = 0
  140.  
  141. while count < 5:
  142.  
  143. time.sleep(delay)
  144.  
  145. count += 1
  146.  
  147. print "%s: %s" % ( threadName, time.ctime(time.time()) )
  148. Create two threads as follows
  149.  
  150. try:
  151.  
  152. thread.start_new_thread( print_time, ("Thread-1", 2, ) )
  153.  
  154. thread.start_new_thread( print_time, ("Thread-2", 4, ) )
  155.  
  156. except:
  157.  
  158. print "Error: unable to start thread"
  159.  
  160. while 1:
  161.  
  162. pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement