[Python] fmap(): a kind of inverse of the built-in Python m →→→→→进入此内容的聊天室

来自 , 2020-11-28, 写在 Python, 查看 194 次.
URL http://www.code666.cn/view/db53e24f
  1. # fmap.py
  2.  
  3. # Author: Vasudev Ram - http://www.dancingbison.com
  4.  
  5. # fmap() is a Python function which is a kind of inverse of the
  6. # built-in Python map() function.
  7. # The map() function is documented in the Python interpreter as
  8. # follows:
  9.  
  10. """
  11. >>> print map.__doc__
  12. map(function, sequence[, sequence, ...]) -> list
  13.  
  14. Return a list of the results of applying the function to the items of
  15. the argument sequence(s).  If more than one sequence is given, the
  16. function is called with an argument list consisting of the corresponding
  17. item of each sequence, substituting None for missing values when not all
  18. sequences have the same length.  If the function is None, return a list of
  19. the items of the sequence (or a list of tuples if more than one sequence).
  20. """
  21.  
  22. # The fmap() function does the inverse, in a sense.
  23. # It returns the result of applying a list of functions to a
  24. # given argument.
  25. # TODO: Later extend the function to also work on a sequence of
  26. # arguments like map() does.
  27.  
  28. import string
  29.  
  30. def fmap(function_list, argument):
  31.  result = argument
  32.  for function in function_list:
  33.   #print "calling " + function.__name__ + "(" + repr(result) + ")"
  34.   result = function(result)
  35.  return result
  36.  
  37. def times_two(arg):
  38.  return arg * 2
  39.  
  40. def square(arg):
  41.  return arg * arg
  42.  
  43. def upcase(s):
  44.  return string.upper(s)
  45.  
  46. def delspace(s):
  47.  return string.replace(s, ' ', '')
  48.  
  49. def main():
  50.  
  51.  print
  52.  
  53.  function_list = [ times_two, square ]
  54.  for argument in range(5):
  55.   fmap_result = fmap(function_list, argument)
  56.   print "argument:", argument, ": fmap result:", fmap_result
  57.  
  58.  print
  59.  
  60.  function_list = [ upcase, delspace ]
  61.  for argument in [ "the quick brown fox", "the lazy dog" ]:
  62.   fmap_result = fmap(function_list, argument)
  63.   print "argument:", argument, ": fmap result:", fmap_result
  64.  
  65. if __name__ == "__main__":
  66.  main()
  67.  
  68. # EOF: fmap.py
  69.  
  70. """
  71. Output of running a test program for fmap():
  72. $> python fmap.py
  73.  
  74. argument: 0 : fmap result: 0
  75. argument: 1 : fmap result: 4
  76. argument: 2 : fmap result: 16
  77. argument: 3 : fmap result: 36
  78. argument: 4 : fmap result: 64
  79.  
  80. argument: the quick brown fox : fmap result: THEQUICKBROWNFOX
  81. argument: the lazy dog : fmap result: THELAZYDOG
  82. """
  83.  
  84.  
  85. #//python/5330

回复 "fmap(): a kind of inverse of the built-in Python m"

这儿你可以回复上面这条便签

captcha