[Python] Filter, Map & Reduce of lists →→→→→进入此内容的聊天室

来自 , 2021-01-10, 写在 Python, 查看 148 次.
URL http://www.code666.cn/view/6e663298
  1. # [SNIPPET_NAME: Filter, Map & Reduce of lists]
  2. # [SNIPPET_CATEGORIES: Python Core]
  3. # [SNIPPET_DESCRIPTION: Simple examples to show common features in everyday work with lists]
  4. # [SNIPPET_AUTHOR: Benjamin Klueglein <scheibenkaes@googlemail.com>]
  5. # [SNIPPET_LICENSE: GPL]
  6.  
  7. numbers = range(1, 20, 1) # Numbers from 1 to 20
  8. #########################
  9. # Filtering of lists:
  10. #       Pick a amount of items which match a certain condition
  11. #########################
  12. # e.g. Get all odd numbers
  13. odd_numbers = filter(lambda n: n % 2, numbers)
  14. print odd_numbers
  15. # prints [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
  16. #########################
  17.  
  18. #########################
  19. # Mapping of lists:
  20. #       Apply a function to each item and return the result of each invocation in a list
  21. #########################
  22. # Calculate the square of two for each number
  23. squared_numbers = map(lambda n: n ** 2, numbers)
  24. # Alternate approach:
  25. squared_numbers = [n ** 2 for n in numbers]
  26. print squared_numbers
  27. # prints [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
  28. #########################
  29.  
  30. #########################
  31. # Reducing of lists
  32. #        Apply a function of two arguments cumulatively to the items of a sequence,
  33. #    from left to right, so as to reduce the sequence to a single value.
  34. #        (Taken from reduce docstring)
  35. #########################
  36. # Sum up all numbers
  37. sum_of_numbers = reduce(lambda n, m: n + m, numbers)
  38. print sum_of_numbers
  39. # prints 190
  40. #########################
  41. #//python/2357

回复 "Filter, Map & Reduce of lists"

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

captcha