构造列表过滤器的 Pythonic 方法

我有一个函数可以根据某些键的值过滤字典列表,就像SELECT * WHERE xxxSQL 中的查询一样


list_of_dict = [

{'key1':val, 'key2':val},

{'key1':val, 'key2':val},

...

]


def filter_list(list_of_dict, key1, key2=None):

    if key2:

         filtered_list = [i for i in list_of_dict if i['key1']==key1 and i['key2']==key2]

    else:

         filtered_list = [i for i in list_of_dict if i['key1']==key1]

但是当我有更多的键作为函数的参数时,if ...else...可能会很长。


有没有更Pythonic的方法来做到这一点?


回首忆惘然
浏览 1563回答 1
1回答

MM们

如果您有大量或可变数量的键,则可以使用all循环遍历它们。下面是一个示例,其中键值作为关键字参数提供:def filter_dicts(dicts, **keys):&nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; d for d in dicts&nbsp; &nbsp; &nbsp; &nbsp; if all(d[k] == v for k, v in keys.items())&nbsp; &nbsp; ]正如 @juanpa.arrivillaga 指出的,dict_items对象在许多方面的行为类似于集合,因此您可以选择过滤具有keys子集的字典:def filter_dicts(dicts, **keys):&nbsp; &nbsp; return [d for d in dicts if keys.items() <= d.items()]例子:>>> dicts = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}]>>> filter_dicts(dicts, x=1)[{'x': 1, 'y': 2}, {'x': 1, 'y': 3}]>>> filter_dicts(dicts, x=1, y=2)[{'x': 1, 'y': 2}]>>> filter_dicts(dicts, y=3)[{'x': 1, 'y': 3}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python