Partitioning a sequence into a dictionary keyed by function values


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.