Posted By

newtonapple on 07/31/06


Tagged

list python function iterator sequence


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

anayhk


Partitioning a sequence into a dictionary keyed by function values


 / Published in: Python
 

  1. def partition(iterable, func):
  2. result = {}
  3. for i in iterable:
  4. result.setdefault(func(i), []).append(i)
  5. return result
  6.  
  7. def group(seq):
  8. result = {}
  9. for item, category in seq:
  10. result.setdefault(category, []).append(item)
  11. return result
  12.  
  13. # def is_odd(n):
  14. # return (n%2) == 1
  15. # l = range(100)
  16. # print partition(l, is_odd)
  17. # print group( (item, is_odd(item)) for item in l)
  18. # print group( (item, item%11) for item in l) # no need to use lamda/def

Report this snippet  

You need to login to post a comment.