Guest User

Untitled

a guest
Sep 20th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. foo = [x for x in bar if x.occupants > 1]
  2.  
  3. >>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]
  4.  
  5. result = []
  6. for index in range(len(numbers)):
  7. if numbers[index] > 5:
  8. result.append(numbers[index])
  9. print result #Prints [12, 34, 67, 37, 9, 81]
  10.  
  11. result = []
  12. for number in numbers:
  13. if number > 5:
  14. result.append(number)
  15. print result #Prints [12, 34, 67, 37, 9, 81]
  16.  
  17. result = [number for number in numbers if number > 5]
  18.  
  19. [function(number) for number in numbers if condition(number)]
  20.  
  21. result = filter(lambda x: x > 5, numbers)
  22.  
  23. result = map(function, filter(condition, numbers)) #result is a list in Py2
  24.  
  25. >>> class Bar(object):
  26. ... def __init__(self, occupants):
  27. ... self.occupants = occupants
  28. ...
  29. >>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
  30. >>> foo = [x for x in bar if x.occupants > 1]
  31. >>> foo
  32. [<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]
  33.  
  34. >>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
  35. >>> foo
  36. [Bar(occupants=2), Bar(occupants=3)]
Add Comment
Please, Sign In to add comment