Advertisement
Guest User

Shenpen

a guest
Feb 10th, 2009
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. #"Project" name: PyNQ
  2. #IDEA:
  3. #LINQ in C# is cool
  4. #Python doesn't quite need it as it has generatior expressions, sum(), len(), sorted() and itertools.groupby()
  5. #so let's just wrap a nice SQL-like interface over them in order to make them more familiar
  6.  
  7. #Problem: all these lambdas suck. Any better ways to do it?
  8.  
  9. #TODOS/QUESTIONS:
  10. #1. is it a good idea?
  11. #2. can it be made to not suck (do something with all those lambdas)?
  12. #3. implement GroupBy()
  13.  
  14. class From(object):
  15.     def __init__(self, lst):
  16.         self.lst = (x for x in lst)
  17.    
  18.     def Where(self, func):
  19.         self.lst = ( x for x in self.lst if func(x))
  20.         return self
  21.    
  22.     def Select(self, func=lambda x: x):
  23.         self.lst = (func(x) for x in self.lst)
  24.         return self
  25.  
  26.     def Count(self, func=lambda x: x):
  27.         return len([func(x) for x in self.lst])
  28.  
  29.     def Sum(self,func=lambda x: x):
  30.         return sum(func(x) for x in self.lst)
  31.    
  32.     def OrderBy(self, func):
  33.         self.lst= sorted(self.lst, lambda x, y: func(x) - func(y))
  34.         return self
  35.        
  36.     def __iter__(self):
  37.         return self.lst
  38.  
  39. #examples
  40. table = ((8, 2, 9), (4, 5, 6), (2, 1, 9))
  41. mySum = From(table)\
  42.         .Where(lambda column: column[2]==9)\
  43.         .Sum(lambda column: column[0])
  44.  
  45. print mySum
  46.  
  47. myLst = From(table) \
  48.         .Where(lambda column: column[2]==9) \
  49.         .OrderBy(lambda column: column[2])  \
  50.         .Select(lambda column: column[0])
  51.  
  52. for item in myLst: print item
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement