t478.py 924 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #map
  2. seq = range(8)
  3. newseq = map(lambda x : x*x, seq);
  4. print newseq
  5. #reduce
  6. rseq = range(16)
  7. rnewseq = reduce(lambda x,y: x + y, rseq)
  8. print rnewseq
  9. rnewseq2 = reduce(lambda x,y: x + y, [], 8)
  10. print rnewseq2
  11. #filter
  12. fseq = range(16)
  13. fnewseq = filter(lambda x: x % 2 == 0, fseq)
  14. print fnewseq
  15. #mapoverstring
  16. def f(x):
  17. return ord(x)
  18. print map(f, "abcdef")
  19. #filter over string returns string
  20. string = filter(lambda c: c != 'a', "abc")
  21. print type(string)
  22. print string
  23. #filter over tuple returns tuple
  24. tup = filter(lambda t: t % 2 == 0, (1,2,3,4,5,6,7,8,9,10))
  25. print type(tup)
  26. print tup
  27. #filter with default identity func
  28. print filter(None, [0,1,"","hello",False,True])
  29. #map with two iterables
  30. b = range(8)
  31. c = range(10)
  32. def mapy(x, y):
  33. if (x == None): x = 0
  34. if (y == None): y = 0
  35. return x + y
  36. print map(mapy, b, c)
  37. #map with default identity func
  38. print map(None, [0, 1, {}, "", "hello", False, True]);