一、引入
个人觉得C#的Linq是非常好用的语法糖,对于List的处理非常方便且高效。但是在Python中没有现成的类似于Linq的类库,于是想着自己写一个。
二、代码部分
1 class LinQUtil(object): 2 """ 3 模拟C#的linq功能 4 """ 5 6 def __init__(self, collection, func): 7 """ 8 初始化 9 :param collection:需要处理的list 10 :param func: 处理的函数 11 """ 12 self.collection = collection 13 self.func = func 14 15 def where(self): 16 """ 17 根据where添加查询 18 :return: 19 """ 20 try: 21 return list(filter(self.func, self.collection)) 22 except Exception as e: 23 print(e) 24 return list() 25 26 def first_or_default(self): 27 try: 28 res = list(filter(self.func, self.collection)) 29 if res: 30 return res[0] 31 else: 32 return dict() 33 except Exception as e: 34 print(e) 35 return dict() 36 def main(): 37 # 从数据库查询出形如[{},{}..]的数据 38 data_list = get_user_list_dal() 39 # 使用Linq匹配到符合条件的数据 40 data_list_where = LinQUtil(data_list, func=lambda x: x.get(‘city_id‘) == 73).first_or_default() 41 42 print(data_list_where) 43 print(len(data_list_where)) 44 45 46 if __name__ == ‘__main__‘: 47 main()
二、总结
这里先简单实现一下where和first_or_default的功能,后面再慢慢补充其他的。。。。。。
其实,实现linq基础类就是基于Python的高级函数 filter()。
使用这里的Linq使我的匹配数据的过程相较于原来使用list循环来做节省了一半左右的时间。
灵活运用python的高级函数如:filter(),map(),reduce()等真的可以大大增加数据处理的效率。
原文:https://www.cnblogs.com/JentZhang/p/12664659.html